the default value of the state is not updated between renders

The default value is intentionally only used when the component mounts. That’s what’s meant by “default”. After that, the only way to change the state is by calling the state-setter function (b in your code).

It’s rare that you need to copy a prop into state, so the likely fix is to just delete the state entirely, and use the prop.

const Child = ({ fn, items }) => {
  React.useEffect(() => {
    fn();
  }, []);

  return JSON.stringify(items);
}

If you do need to have state for some reason, first consider if you can move that state up to the parent and thus eliminate this issue. If for some reason you can’t do that either, then you’ll need to have the child implement logic which calls the state setter b when you want it to be called. For example:

const Child = ({ fn, items }) => {
  const [a, b] = React.useState(items);

  React.useEffect(() => {
    b(items);
  }, [items]);
  
  React.useEffect(() => {
    fn();
  }, []);

  return JSON.stringify(a);
}

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top