I am currently using reactjs with redux and I am a newbie.
In my current code I have an object which gets passed through to the under lying code. I want to avoid this and have it in the props so I do not need to nest it. Is this achievable using reactjs?
Example:
module.exports ({ obj1 }) return <ul text: obj1></ul>
This goes further down into other method calls.
Should I expand the object props and avoid passing the full object down?
I definitely think you should expand the object and only pass down the props required by your child components. This way you allow for the development of components with minimal responsibility, which promotes reuse. It's a common pattern to create Container and Presentational components.
Dan Abramov, the creator of Redux, has some amazing egghead tutorials which will help you for sure. Check them out here:
https://egghead.io/courses/getting-started-with-redux
And when you have built up some experience, check out his newer set of lessons which deal with some more advanced concepts (stick with the first lessons though until you have a proper grasp of Redux).
https://egghead.io/courses/building-react-applications-with-idiomatic-redux
The context API was purposefully designed for passing data through the component tree, while still retaining existing behavior related to properties.
Related
I am working using useContext in React. Today, I recognized that I am using too many useState in useContext. I was looking for the answer, but I could not find it.
I know it is a silly question, but please answer my question if possible.
Thank you.
Thank you for the answers to my question. So, I understand that if there will be many states in useContext, it is a good way to use useRedux.
This is my opinion. I think there is no such thing as too much as long as your states are relevant with what you are doing. It depends on what is your purpose when using the createContext. But make sure to organize them well so that they are still modular and not mixed with other context of states.
For me, I draw a simple borderline where if I'm only making some one-off reusable components that need control from far away (e.g. Dialog which can be toggled by deeply nested button), then I should create a context that has just enough states for that component. Whereas if I want to store some states which I want to access from multiple places, especially if it is related to business logic, then I prefer to use Redux instead.
I think useContext and useState are different functions:
useContext: This is a hook that returns values from the context that has been kept. Any change in values causes the react component where this hook is placed to rerender.
useState: a hook that declares the react component's state.
I think I understand what you mean when you say you declare many states in the context. Some best practices you need to consider are:
Using useReducer hook to group & manage the change of states. It makes it easier to control the changing of states. It is obvious that the state shifts with each individual action.
You need to review the total state that is declared. Only keep states that need to be shared in that context.
Refer: read more in react js docs about context api & declare a state in react component.
So, i know the difference between the two but after hooks i'm kinda confused about when i should use stateless and when use statefull.
When i was learning the basics of React i was told that stateless is the "dumb" function and statefull is "smart". And that i should use stateless in simple things, because props are imutable and also use more than statefull. I dont really know the difference with Hooks changes in 16.8.
I know that we can use setState now but i dont understand it totally.
This is a great question, and one that I think people will have trouble with for a while. The way I see it, the term "stateless" has been dropped from regular component verbiage and they are just called "functional components".
The concept of "stateless" is still very important though, because it involves no inner state that does not mimic its props. As you said, they are dumb. Generally, if a component can be stateless, it will be more performant. Components that are rendered in loops with a high count do much better with this type of structure. On the other hand, don't stress too much about performance until you're hitting bottlenecks, which shouldn't happen until you've got thousands (or more) of components rendering at once.
To address hooks- they allow you to "hook" into the state and lifecycle of a component. As you will see in the docs, they do not offer more functionality, but a simpler API. This leads to cleaner code and more reusable custom hooks.
If you are dabbling with hooks, maybe try it on some new components you need to build. I've found it to be fun and simplifies my code considerably.
As a final answer, I would say that the concepts of "stateful" and "stateless" components is the same. Only the API that allows you to utilize state has been changed.
Your 'dumb' components should remaing dumb.
Your 'smart' components, can take advantage of hooks to make them 'dumb' with a hint of smart.
Imagine a component where you have to make it 'smart' because there is a toggle in it.
With the old way, you would create a component that has State.
With hooks, you can create a dumb functional component, that just happens to use the hook useToggle.
This keeps your code simple and concise, while at the same time keeping the same functionality you used to have building smart components.
Hooks are just another means to use state (and other functionality) in a so-called "smart", functional, component. That said, their existence doesn't change the answer to this question (of which, there are many).
One example of an appropriate use of state is when you have a component that will render different output based on some sort of change to the component after the initial render. More specifically, if you have a component that needs to make a network call to fetch some data for display, you could use state to keep track of the initial non-existence of that data and update it when the network call returns using setState.
In my experience, as a general pattern, you should use state for things that change and props for things that don't.
I think, the question is actually simple, when do we use the state hook in react? The answer is, if you write a function component and realize you need to add some state to it, now you can use a state hook inside that existing function component. Previously you had to convert it to a class component.
Then why don't we use the class component from the beginning instead of function component? Because when it was first introduced, the recommended pattern for react developers was to use as many stateless components as possible, in other words as many function component.
And in my personal opinion, the function component is neater and easier to use, maybe even more suitable with the reusable component concept. So then, yeah, now we can expand the use of the function component even more.
Hope it helps
I'm using Redux, Immutable.JS, and React. I want to pass an Immutable.JS list into my stateless React component. This component maps through the list and renders a child per item in the list.
Example:
function Cats(props) {
function Cat(p) {
return <li key={p.id}>p.name</li>;
}
return <ul>{props.cats.map(Cat)</ul>;
}
The {p.id} part breaks, because props.cats is an Immutable.JS list of maps, so I'd have to update my React component to say {p.get('id')} instead.
I'd be okay to do this, but are there better ways for a stateless React component to consume a list without having to know that it's an Immutable.JS list? This usage violates the best practice in the Redux + Immutable.JS + React best practice, "Use Immutable.JS everywhere except your dumb components". 1
I'm certain other people have dealt with this problem and I don't want to reinvent the wheel.
Can relate with your pain, I have documented this here - What are disadvantages to using immutable state in React?.
For Redux
You can use mapStateToProps to convert immutables into normal JS (state.toJSON()). So the dumb (don't like that term) components should be abstracted from the actual structure of your state.
Otherwise
This is an issue anywhere you want abstraction between your state library and your views. One way I have been able to isolate this to some extent is to use (lenses)[https://medium.com/#drboolean/lenses-with-immutable-js-9bda85674780]. If they seem too complicated, you can make a get([key path], source) method and send that in props to your components and use it to fetch the value. This at least provides some abstraction.
You are not wrong.
If using ImmutableJs what you should do is p.get('id') the other way would be something like props.cats.map(elem => <Cat id={elem.get('id')} key={elem.get('id')}/>)
or IMHOP less elegant props.cats.map(elem=>elem.toJs()).map(Cat) but its just different ways of doing the same thing.
Hope it helps
How to do this easily ? I uses Angular so I don't usually think about this problem as Angular does it automatically. in Angular, I can pass a variable from controller down to any "children" directive in any depth, and when that variable is changed, it permeates in all directives and controller who use it.
In React however, one must use callback which is then passed through layers of React component: passing data from child to parent component - react - via callback function.
I use the above solution to pass a single variable through 3 different React components :
APP --> TABLE --> ROW_TABLE
EDIT: It is not that I don't understand how to pass the variable through layers of component. I just think there must be more easier way to do this.
I think this solution is quite complicated. Keep in mind that we usually deal with more than three "components" in the real life. Can someone give me suggestion of how to do this 'right' ?
I'm just learn React for a day now so I must miss something. Thank you
If you want to pass a variable through many childs, the most correct way of doing it in React is just passing them through props.
If you don't want to use this aproach you could use state management libraries like redux.
If you want instead to do this using pure React you could use the component's context, although it is not recommended.
See more about context here https://reactjs.org/docs/context.html
Would like a bit of knowledge gain with your help on this one. Just to clarify, I'm still educating myself with Reactjs.
I have two components, A and B. I need to access A's state from B. Is that possible?
var A = React.createClass({
getInitialState(){
return {foo: 'bar'}
},
...
});
var B = React.createClass({
getInitialState(){
return {x: 'y'}
},
render(){
var a = <A />;
var b = a.state.foo; // This was just a guess but I dont understand the docs for something like this.
return({b});
}
});
In B's component, how to render A's state, which is bar? I wish to have two separate components.
I have been reading about ref but still can't figure out how to accomplish what I want with refs.
React version: 0.14.3
Let's look at the purpose of state and props. A component's state is completely internal to a component. It is never known outside of the component and may/not be passed down to the children components (as props). Props on the other hand are explicitly public and are merely consumed by the component. They should be the only means of passing information down to a component.
While designing your components, always consider this that any data required by more than a single component cannot be a state of any one of them. React encourages unidirectional data flow and accessing state across different components violates that, thereby making your components difficult to reason with.
In your case, since B needs to know some information which A has, I suggest something like this -
A publishes this information to a Flux store at an appropriate time.
B has subscribed to the same Flux store, it gets notified of this
information and updates itself.
#HazardousS and #DERIIIFranz are wrong.
In reply to #HazardousS, just because you need data to go from one component to another does not warrant implementing Flux into your app. You always want to use props, then state, then... Flux. The lesson here is, "Only use Flux if you need to." Pete Hunt, an earlier Facebook-er who worked on React published this last week. It disspells a lot of the hype and misinformation in the React community: https://github.com/petehunt/react-howto
In regards to #DERIIIFranz about using Context: DO NOT USE CONTEXT. If you just click on the link the Facebook docs even have a warning for its own feature. It's something cute that the React docs does... they give you a lot of rope to hang yourself with.
It seems like you haven't gone through the React tutorials yet because you're asking basic questions about data messaging. This is something you need to understand in a fundamental way if you want to succeed in React. Put in the time, do the tutorials on the Official React docs page, and get familiar with the "React Way" of doing things. It's weird, and odd... but it'll click if you buckle down and sink in the time to learn the fundamentals.
We have to think of ways to make available the this.state.somevariable of <A/> inside <B/>.
If <A/> and <B/> are siblings of a common <Parent/>, the parent can change this state for both <A/> and <B/> and pass the changed state as this.props.statevariable to the children.
If <B/> can be a child of <A/>, <A/> can always pass its this.state.statevariable as props to <B/>.
If you go through the Flux Architecture, you can maintain these variables required for rendering inside the Stores and access these in as many components as you like.