2

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!

assembler
  • 3,098
  • 12
  • 43
  • 84

1 Answers1

1

Try to make your update function memorized with useCallback

const update = useCallback((item, value) => {
    setData((prevState) => ({
      ...prevState,
      [item]: value,
    }));
}, []);
Arthur Arakelyan
  • 164
  • 1
  • 11
  • Yes, this works, thanks, but what I really need is to memoize the children component. Although you need to pass `data` into the dependencies array for this callback – assembler Oct 17 '22 at 16:12
  • It is possible only with useCallback, because when the children component doesn't take functions as props. Functions are updating after every re-render – Arthur Arakelyan Oct 17 '22 at 16:13
  • I am telling the component what are the props to observe – assembler Oct 17 '22 at 16:14
  • 1
    @assembler these links might be helpful for you. https://dmitripavlutin.com/use-react-memo-wisely/ https://stackoverflow.com/questions/63123846/react-memo-2nd-parameter-dependency-function-not-working-as-expected – Arthur Arakelyan Oct 17 '22 at 16:17
  • 1
    with **prevState** there is no need to pass **data** as an argument for callback – Arthur Arakelyan Oct 17 '22 at 16:26
  • 1
    You know what, your response works charmingly – assembler Oct 19 '22 at 17:41