Ensuring Child Component Reloads When Parent Component Changes - reactjs

I am working on creating an updated implementation of an existing react native app and am running into a situation where a child component doesn't re-load when the parent component changes.
My situation is this: I have a parent component for a particular record. Connected to this is a VisitTimer child component that keeps track of duration for a that record's session. What I'm noticing is that, when I load a record into the parent component for the first time, the child component <VisitTimer> does fire with componentDidMount(). However, if exit that screen, and load a DIFFERENT record, then the child <VisitTimer> component does not mount - i.e. componentDidMount in the VisitTimer child component does not fire.
What is the likely issue here? And how can I ensure that a child component always re-mounts when the parent component changes?
Here is the child component within the parent:
<VisitTimer
started={this.props?.session?.dates?.started?.value}
stopped={this.props?.session?.dates?.completed?.value}
durationOverride={this.props?.session?.duration?.total?.value}
maxDuration={maxVisitTime(this.props?.session?.type?.value)}
visit={this.props?.session}
ref={(ref) => (this.visitTimer = ref)}
stopTimeOffset={this.props.visit?.duration?.stopOffset?.value}
editable={statusCodeToEditableLevel(this.props.session?.status?.value) === 2}
onChange={this.onSessionTimerChange}
/>

See my comments but a way to force this to be recreated is to give it a unique key based on the record. In react, key is special, and if it changes the whole component will remount. You could set the key to a unique id from the record:
<VisitTimer
key={this.props?.session?.guid}
started={this.props?.session?.dates?.started?.value}
stopped={this.props?.session?.dates?.completed?.value}
durationOverride={this.props?.session?.duration?.total?.value}
maxDuration={maxVisitTime(this.props?.session?.type?.value)}
visit={this.props?.session}
ref={(ref) => (this.visitTimer = ref)}
stopTimeOffset={this.props.visit?.duration?.stopOffset?.value}
editable={statusCodeToEditableLevel(this.props.session?.status?.value) === 2}
onChange={this.onSessionTimerChange}
/>
I made an assumption the unique id is on session.guid.
By the way, this is generally a good idea over implementing componentDidUpdate in your situation. People often go that route and spend loads of time implementing reset behavior to set the state back to its original values, which is a source of bugs. Changing key guarantees you have a fresh start. The only time you shouldn't do this to achieve a "reset" on a component is if remounting it and its children are expensive.

Using a key will force a re-render but that's not the primary purpose of key. React docs do talk about using the key like this but those are for specific use cases. In this case I would encourage to ask ourselves:
Do we really need to re-mount the child component or do we just want it to re-render
Regardless of the answer to the above question. Why do we need the child component to re-render. Is it because it needs to show an updated data?
If yes, then the child component should receive a prop from the parent or something from a global state which changes (in your case probably the record itself). That kind of prop change/state change will automatically trigger a re-render
I hope this is helpful but the community can be even more helpful if you can share more details of your problem like - What does the parent component do, what does the child render, why do we want the child to re-render, etc

Related

React component state becomes invalid after change in parent component

function UserCard({ user }) {
let defaultUserName = user.nicknames[0];
let [selectedNickname, setSelectedNickname] = React.useState(defaultUserName);
// The selected nickname becomes invalid when the user is changed!!!
const selectedNicknameIsValid = user.nicknames.includes(selectedNickname);
return (<div>
<UserCardWithNickName user={user} selectedNickname={selectedNickname} />
<SelectNickName user={user} setSelectedNickname={setSelectedNickname} />
</div>);
In the above snippet the component's state holds the selected nickname from the list of user nicknames. But when the user changes in the parent component this component is re-rendered with the same state. So the nickname in the state is for the wrong user.
What is the preferred way to handle this? A lot of google searching couldn't find much discussion.
Am I doing this in some fundamental non-react way?
Is the preferred solution to use useEffect to fix the state when it becomes invalid as discussed here React.useState does not reload state from props?
Working example on codesandbox
Yeah, state changes in the parent component will usually re-render the child component, and hence reset the state of the child component. I'd suggest moving states that you want preserved up into the parent tree.
State management is an important concept in React. As your app grows, you'll realize doing this will add a lot of bloat and repetitive code. Learning about state management will prove very useful for you!
Yes. The link you have posted is one way to do it. The question you have to look for is if your child component is managing the value of selectedNickname in anyway. That is the only reason you would want to keep it as a seperate state in the child component. If all it does is read the props from the parent, simply use the props and do not maintain an internal state at all.
Months later I finally found a robust discussion of this problem in the react docs.
https://reactjs.org/blog/2018/06/07/you-probably-dont-need-derived-state.html
The problem I was trying to describe is called derived state.
I eventually solved it by adding a key when using the component. When a key changes, React will create a new component instance rather than update the current one. This is one of the recommended approaches in the docs.
<UserCard user={user} key={user.id} />

Mount a child component once in a lifecycle of React app and use the same instance whenever needed

I have scenario where the grand child or great-grant child component needs to be mounted only once . And once it gets mounted , the same component can be reused whenever needed instead of mounting it again and again.
how to achieve this in REACT ?
No, you actually can't do that in React.
The idea is that whenever a component is not "needed" (meaning it's not being currently viewed, a case you just cannot modify, it's one of the React fundamentals), it is being unmounted (to improve performance). So, in consequence, when you enter it again, React renders (mounts) it again, from scratch.
The only solution I can think of is disabling the component from being unmounted, which means disabling the components' change; and this is most certainly not something you asked for...

Re-render logic for children of parent which updates muliple times per second

So I have a component which the state is updated multiple times a second by a child element.
To prevent over-rendering i use the shouldComponentUpdate on the other children to make sure they don't re-render too much.
The element of the state that is updated is required by another child further down the tree.
I would only like that child element to rerender, and not the intermediary children, again, to avoid over-rendering.
How could one do that?
I would only like that child element to rerender, and not the intermediary children, again, to avoid over-rendering. How could one do that?
You can't via the traditional method of passing the state down as props. A change in state in the parent component cannot trigger a re-render on the grand-child component C without triggering a re-render on the child component B first.
For a component to update a child, it needs to go through its life-cycle before it can pass down new props to it.
To my knowledge, the only way around this is to use a state management library, such as Redux or MobX, or use the React Context API and move that state variable there and then "consume" it in your grand-child component.
That being said, unless your tree is multiple levels deep and you don't see any performance issues, I would consider keep using shouldComponentUpdate() like you are already doing.

throw error after everything is rendered in react

I am trying to create a react HOC that would render its children, and then after all the children had finished updating BUT BEFORE THE DOM is updated, would decide to raise (or not raise) an error, depending on some flags the children would update.
<Try alternative=... >
... do some stuff // if anybody in here sets a flag we will
// render alternative instead
</Try>
Why? It would be useful to allow all the children of Try to complete rendering and then if any were waiting on some async callbacks, to render the alternative. Kind of like an error boundary but it would all the enclosed children to re-rerender first.
Having the first child that hits the condition raise an error doesn't work, since it doesn't allow the rest of the children to finish.
Using an componentDidUpdate handler in Try won't work either, since it won't run unless Try actually changed (I think).
I am hoping somebody will know of a secret, or expermental trick that might work.
Thanks
I think you are over-complicating things. Why not take a simple approach that achieves the same goal?
Your callbacks will set some sort of state. So that means, if the state has not been set, the callback has not been run.
In your child components you can check to see in the state has been set. If the state has not been set; then, display your "Please Wait" message.
The "Please Wait" message can be extracted into its own component and be used throughout the entire website. By extracting the code for the "please wait" cover, all components can then use it instead of implementing their own version of the "please wait" cover.
I think this is a lot more simply and effective then what you are suggesting.
EDIT:
Regarding the flickering mentioned in comments. That shouldn't happen. Where I was trying to go is have a "Cover" component for the "Please Wait".
The child component would check it's state to see if it is ready to display it's main content. If not, the child component would use the Cover component.
In otherwords:
Child Component is constructed
Child Component's State is not ready. Child uses Cover component
Child Component's State changes (due to async callback)
Child Component Starts Re-Render Process
Child Component's State is ready to render main content
Child Component renders its own content
This is fundamentally different from what your comment had said. The parent would not render the Cover. The child would use the Cover component when it is not ready to render its own content.

React: Parent component re-renders all children, even those that haven't changed on state change

I haven't been able to find a clear answer to this, hope this isn't repetitive.
I am using React + Redux for a simple chat app. The app is comprised of an InputBar, MessageList, and Container component. The Container (as you might imagine) wraps the other two components and is connected to the store. The state of my messages, as well as current message (the message the user is currently typing) is held in the Redux store. Simplified structure:
class ContainerComponent extends Component {
...
render() {
return (
<div id="message-container">
<MessageList
messages={this.props.messages}
/>
<InputBar
currentMessage={this.props.currentMessage}
updateMessage={this.props.updateMessage}
onSubmit={this.props.addMessage}
/>
</div>
);
}
}
The issue I'm having occurs when updating the current message. Updating the current message triggers an action that updates the store, which updates the props passing through container and back to the InputBar component.
This works, however a side effect is that my MessageList component is getting re-rendered every time this happens. MessageList does not receive the current message and doesn't have any reason to update. This is a big issue because once the MessageList becomes big, the app becomes noticeably slower every time current message updates.
I've tried setting and updating the current message state directly within the InputBar component (so completely ignoring the Redux architecture) and that "fixes" the problem, however I would like to stick with Redux design pattern if possible.
My questions are:
If a parent component is updated, does React always update all the direct children within that component?
What is the right approach here?
If a parent component is updated, does React always update all the direct children within that component?
No. React will only re-render a component if shouldComponentUpdate() returns true. By default, that method always returns true to avoid any subtle bugs for newcomers (and as William B pointed out, the DOM won't actually update unless something changed, lowering the impact).
To prevent your sub-component from re-rendering unnecessarily, you need to implement the shouldComponentUpdate method in such a way that it only returns true when the data has actually changed. If this.props.messages is always the same array, it could be as simple as this:
shouldComponentUpdate(nextProps) {
return (this.props.messages !== nextProps.messages);
}
You may also want to do some sort of deep comparison or comparison of the message IDs or something, it depends on your requirements.
EDIT: After a few years many people are using functional components. If that's the case for you then you'll want to check out React.memo. By default functional components will re-render every time just like the default behavior of class components. To modify that behavior you can use React.memo() and optionally provide an areEqual() function.
If a parent component is updated, does React always update all the direct children within that component?
-> Yes , by default if parent changes all its direct children are re-rendered but that re-render doesn't necessarily changes the actual DOM , thats how React works , only visible changes are updated to real DOM.
What is the right approach here?
-> To prevent even re-rendering of virtual DOM so to boost your performance further you can follow any of the following techniques:
Apply ShouldComponentUpdate Lifecycle method - This is applied only if your child component is class based , you need to check the current props value with the prev props value ,and if they are true simply return false.
Use Pure Component -> This is just a shorter version to above method , again works with class based components
Use React memo -> this is the best way to prevent Rerendering even if you have functional components ,you simply need to wrap your components export with React.memo like : export default React.memo(MessageList)
Hope that helps!
If parent component props have changed it will re-render all of its children which are made using React.Component statement.
Try making your <MessageList> component a React.PureComponent to evade this.
According to React docs: In the future React may treat shouldComponentUpdate() as a hint rather than a strict directive, and returning false may still result in a re-rendering of the component. check this link for more info
Hope this helps anyone who is looking for the right way to fix this.
If you're using map to render child components and using a unique key on them (something like uuid()), maybe switch back to using the i from the map as key. It might solve the re-rendering issue.
Not sure about this approach, but sometimes it fixes the issue

Resources