Search code examples
reactjsrendermemoizationmemo

React js memo is not working as expected after passing props from parent to children


Lets say I have a component that maintains the state of some children components. This component holds an update function that contains the logic for update the state. I pass the state and the update function to the children component, that are memoized. The thing is the state is not being updated, or the state is cleared after the last change is made.

My question is how to proceed with this memoization, due to the real one has a lot of textfield to update.

In this sandbox I reproduce a minimum example.

Cheers!


Solution

  • Try to make your update function memorized with useCallback

    const update = useCallback((item, value) => {
        setData((prevState) => ({
          ...prevState,
          [item]: value,
        }));
    }, []);