Saturday, 19 February 2022

What is the status of the 'default props rerender' trap in React?

I'm looking for a canonical reference to how this has been dealt with.

If I have a component that looks like this:


const MyComponent = ({ value = [] }) => {
  const [otherValue, setOtherValue] = React.useState([]);

  React.useEffect(() => {
    setOtherValue(value);
  }, [value]);


  return <div> doesn't matter</div>
};

What happens is:

  1. When value changes, the useEffect callback fires, and this calls a setState
  2. The setState causes a rerender, if value is nullish, then the default array is assigned, and this is a new object, and so this in turn, causes a rerender.
  3. Infinite loop.

The solution can be to declare your default prop as a constant, like:

const DEFAULT_VALUE = []; 
const MyComponent = ({ value = DEFAULT_VALUE }) => {
  const [otherValue, setOtherValue] = React.useState([]);

My questions:

For each of the version 16, 17, 18 of React:

  • Is this an issue that has been solved? If, so which version solved it?
  • If it hasn't been solved, a pointer to the 'won't solve' decision.
  • Is there an eslint rule to capture this?
  • Anything else that is generally helpful in avoiding this trap.


from What is the status of the 'default props rerender' trap in React?

No comments:

Post a Comment