React: is accessing the state of children an anti-pattern? - reactjs

I've got a component that needs to read a state variable belonging to its child at some point.
Should this particular state variable rather be moved to the parent, and be changed via a callback?
As I see it, and some of this is likely wrong, these are the pros and cons of moving the state to the parent:
Pro:
This seems to adhere more to the unidirectional data flow mantra of react.
Con: Other children of the parent will be rerendered on state change (not in the real DOM, but it may still have a performance impact).
What is the best practice here?

Best practices for data flows are:
From parent to child: via props
From child to parent: via handlers
From unrelated component to another: via message bus
e.g.
<Child onEvent={this.handleEvent}>
The parent has:
handleEvent: function(dataFromChild) {
}

As Petka noted, state should live on top.
Thinking in React explains it well.
Other children of the parent will be rerendered on state change (not in the real DOM, but it may still have a performance impact).
You're unlikely to notice this unless you do this at 60fps.
And if you do, React has you covered with optional shouldComponentUpdate (and PureRenderMixin).

Related

Trigger a function in a child component

There is some related threads, and a lot of opinions on this subject so I will try to summarize my findings. Notice I am a beginner so this is my best bet, and the data I gathered from related posts and this.
In general most people agree that if the parent call's a child it is bad practice. In the related post for this article there is an accepted answer, where the person answers that it is a bad practice but possible. #mat sz answer directed me on the right path. I have updated my sample for others to see. I pass a parameter to my child component. In the child component I add a listener for changes on that parameter:
useEffect(() => {
if (props.toggleClose != null) {
setToggleJobTable(false);
}
}, [props.toggleClose]);
I just toggle that parameter between true/false in my parent. Not beautiful but my best bet on how to do this in react.
Original question
I found a lot of samples in here on how to pass variables to child components, how to raise events from child components to parent components, and even how to pass a function to a child component from parent component. But what about last scenario. How to call a function in a child component from the parent. In this sample I would like to trigger the closeAll function in the child component from the parent:
https://codesandbox.io/s/toggle-all-qxkgy?fontsize=14&hidenavigation=1&theme=dark
I still dont have an answer on this, but a lot of good input in the posts. For me it sounds like the right approach here would be parsing a parameter to the child as parameter. My question is then, if I pass a parameter to the child component. How do I toogle when the parent changes that value, then my closeAll function in the child is called?
It is also stated that it could be wrong design. If you look on my very simple sample how should it else be designed? All input are welcome. I have very little experience with REACT so I am trying to understand how an experienced REACT developer would solve this simple task/sample.
It's not possible, parent components are not able to access the functions inside of child components.
You could use something like Redux or MobX to create a global state and then rely on global state for that, or you, ideally, should restructure your code in a way that does not require this, for example if your function (the one that has to be called inside of parent) changes state of a child component - move that state to the parent component, and then provide that state via props to the child component (along with a setter function, if required).

How can I call child component setState from parent component

I have 2 stateful class-based components nested within my main app, a parent class-based component. From child component 1, I've successfully called a parent callback method. From within that parent callback I want to call a method of child component 2, so I can setState of #2 without re-rendering the parent component. I've seen that many devs make the children stateless or even just omit them. However, React encourages devs to "componenatize" ... pointers plz!
if that's the case then you shoud consider lifting the state up to the parent: https://reactjs.org/docs/lifting-state-up.html
your child component should only then call parent methods to update the state, that way, you will have a unidirectional flow of data as what a react app should be. Basically, it encourages you to have a single source of truth and ensure synchronisation of data across your app. Besides it removes unnecessary logic like what you are doing right now:
What does the "single source of truth" mean?
Storing the data in the parent's state and then allowing both children to update it via setStates wouldn't violate the concept of "componentizing" as long as the two children have narrowly declared inputs. If one child needs to update data inside another child, you can jump up a context level and store it in the parent- then an update of the data from either child will trigger a render of both children ensuring the display stays synchronized with the data while keeping the data in a single place (with the parent instead of split between the children).
Bingo, yes I can use a "React ref" to call an instance method of a child component. A ref is an attribute on a component instance. So, right now my child component uses its componentDidUpdate to call a callback in my parent, and the parent callback then uses refs to call an "update" method of specific child components. These update methods setState on child component and voila.
So a colleague explained that calling setState in my main app actually will call setState on all children components (related by JSX expressions). Even though I liked the idea of nesting my event handlers within their relevant child components, it seems that the best practice pattern is to have all handlers in the main app, setState in the main app, then let React do its thing

In reactjs, are props pass by value or pass by reference?

As far as I can tell, if I pass a parent component state down to a child, then that child gets the live state of the parent.
So a change made in the state of the parent is immediately also available in the child via the prop that it came on.
Is this correct?
It's basically the same mechanism as anywhere else in the language, as you'd expect. Primitives are passed by value and variables that aren't primitives will be passed by reference.
React takes care internally of the updating of props, so that children always have the most up-to-date value of the prop.
This is the lifecycle method that is called when receiving new values for props.
However, make sure you respect the infrastructure put in place and the exposed API that React gives you.
Short answer: props are passed by reference.
The reason it can be confusing: if you change the parent's state by hand (bad practice!), the object will change in the child component, too. But won't trigger re-render! (The child component won't "know" that its props has changed.) So you won't see the UI change.
However if you change the parent's state with setState (the preferred practice), the child will be notified, that it must re-render itself.
If you pass down the state of the component as props to its child, then if the state of the parent component changes it re-renders, which will also re-render its children with the refreshed properties. The children don't directly listen for the state change like the parent does, they are simply re-rendered as as result of its parents state change and updated.
Take a look at this - https://facebook.github.io/react/docs/multiple-components.html. It will help you get your head round how this concept works. Hope this helps!
When the state of a component is changed, then the component is re-rendered by React. While doing that , its child components are also re-rendered, which causes changes in them also.
No, they will not be duplicated, you will access to those props by reference, because they come from a single object wich defines them, and then pass them as a reference to the child objects.
You can take a look to the official documentation here: https://reactjs.org/docs/react-component.html.
I suggest to use a stateless mechanism to handle large data, expecially if shared.
Personally I use mobx (https://github.com/mobxjs/mobx) wich is a great framework to create stateless apps.
With this method you can handle data and state updates in a single component, called Store, and use components to render html only, and not to handle data, wich is a great boost on application performances.

Transfer props to children without re-rendering parent

Is there a React-okay way to pass new props to children without re-rendering the parent? Nothing in the parent component is changing except that new props are being passed to that component which are being passed through to its children. I thought context might be appropriate in this situation but it seems like the documentation states otherwise.
It depends what you mean by React-okay. You can in fact use contexts for this, but I don't recommend it. It's much easier to reason about and debug props flowing down directly through your view hierarchy, and if the parent isn't changing at all the render function should be quite cheap to execute.
If it isn't cheap, you may want to rethink how you're structuring your components. For example, you may want to split off the expensive part into a separate component that only gets rendered when relevant props have actually changed, or at least secure the expensive functionality behind a conditional props check.

Is it More Performant to Pass Props From Parent Component Or Listen to State Change In Flux Store?

Let's say I have the following parent -> child relationship(s) inside of a react component:
<parentComponent>
<childComponent>
<grandChildComponent>
<greatGrandChildComponent></greatGrandChildComponent>
...
...
... // And so on
</grandChildComponent>
</parentComponent>
Assuming I'm getting data from a Flux store, is it more performant to have <parentComponent> get its state from / listen for changes on the Flux store and then pass the relevant data down to its children as props or is it more performant to have each <..child> component listen to the store directly for any updates to its state?
Performance would likely depend on your specific program. Is there a reason youre concerned with performance between these two practices? I must imagine its an extremely minimal difference.
that being said, idiomatic react greatly favors stateful components housing stateless components. unless theres a good reason for a child component to manage itself (that is manage its own state and not let its parent manage it), you should be composing your site with as few stateful components as possible that contain many stateless children.
tl;dr pass in props from your parent

Resources