Avoid parent component re-rendering when Child component updates parent state,
Asked Answered
G

1

7

In our react application, We have parent-child component. Child component calls parent method to update parent state values. Here is sample code

//Parent component

const parent = ({ items }) => {
    const [information, setInformation] = useState([]);
    const updateParentInformation = (childUpdate) => {
         setInformation(information + childUpdates)
    }
    return (
        <div>
            <div>{information}</div>
            ...
            {items.map((item) => {
                return (
                    <ChildComponent item={item} updateParentInformation={updateParentInformation} />
            )})}
        </div>
    )
}

//Child Component

const ChildComponent = ({ item, updateParentInformation }) => {
    useEffect(() => {
        const cardInformation = calculateCardInformation(item)
        updateParentInformation(cardAmpScripts)
     }, [item])
    return (
        <div>
            .....
        </div>
    )
}

So child component calls the parent's updateParentInformation function to update the parent state, which re-renders parent components. I have a few questions here

  1. In some cases, we may have 100-150 Child components, in such cases our parents will re-render a lot, How to avoid this. We can avoid this throgh this code

    ....
     let recievedUpdates = 0
     const updateParentInformation = (childUpdate) => {
          recievedUpdates++
          if(recievedUpdates == items.length {
              setInformation(information + childUpdates)
          }
     }
    

If this is a possible solition then I have question 2

  1. How to avoid race-condition when child component calls parent's updateParentInformation. For example child 1 is called updateParentInformation function and at the same time child 2 is also called updateParentInformation, in this case we may lose updates from one child.
Gaultiero answered 11/4, 2022 at 15:41 Comment(2)
For the first question you can use React.memo() (reactjs.org/docs/react-api.html#reactmemo) in order to have a component rerender only if his props has changedSeducer
Could you create a runnable minimal reproducible example on codesandbox.io or similar? I'd be able to get some eyes on the behavior.Cardiomegaly
S
6

You CAN'T avoid that since a Component always has to re-render if its internal state changes. So you have two possible approaches to solve performance issues in this scenario:

  1. Wrap your children in React.memo(), this way every time one of your children updates a state in the Parent component, all the children that don't care and don't receive that updated state as a prop, won't re-render.
  2. Use a global state manager ( Suggested ). If you have hundreds of components that use common states, and maybe those states are drilled through props, causing a lot of unnecessary re-renders, you will definitely get advantage of a State Manager, like Redux, this way only the components that use a particular slice of the state will re-render when that state changes.

In any case, if in your Components that are on top of the Tree, ( Parents ) you perform heavy calculations, always wrap them in useMemo() hooks, same goes with functions and useCallback(), this way you will be able to address most of your performance issues.

Regarding the question about race-condition, react useState can be used with a callback like this, to be sure that when it executes it will have access to the most up-to-date value of that state in that moment:

const [state, setState] = useState(0)
setState(currentState => currentState + 1)
Send answered 11/4, 2022 at 16:29 Comment(2)
why do you suggest using a state manager like Redux over useMemo? Are these managers doing something different under the hood or does it just make it easier to implement? ThanksAbortionist
@Abortionist Avoiding unnnecessary renders is just one of the positive aspects of using a global state manager. As I wrote, if you have hundreds or thousand of components sharing states it becomes totally unmantainable to drill props, using context and memoizing. State managers do what they promise to do "Manage application state". Under the hood they often use quite different technologies and approaches.Send

© 2022 - 2024 — McMap. All rights reserved.