react.dev icon indicating copy to clipboard operation
react.dev copied to clipboard

code example seems to have an extra dependency: onChange

Open devmi opened this issue 2 years ago • 1 comments
trafficstars

I believe the onChange event handler shouldn't be declared as a dependency on the following useEffect example, because although this is a prop, its value should not change, so it's not a condition for the effect to run. Although it may be harmless, it may confuse other learners.

https://github.com/reactjs/react.dev/blob/10574e59a81425e9e8f63f0b094d09e3636b3198/src/content/learn/you-might-not-need-an-effect.md?plain=1#L519

Suggested change:

// 🔴 Avoid: The onChange handler runs too late
useEffect(() => {
  onChange(isOn);
}, [isOn])

devmi avatar Oct 18 '23 21:10 devmi

Hey @devmi 👋

I'm not sure I agree.

  1. In practice, the onChange prop may never change, but there's no way to guarantee that.
  2. I think it would be more confusing to users to directly contradict the useEffect documentation.
  3. It raises an error to remove the dependency:

image

Thanks for the feedback though! ❤️

pwbriggs avatar Feb 16 '24 14:02 pwbriggs

Agree with @pwbriggs. As the docs here say, you don't “choose” the dependencies of your Effect. Every reactive value used by your Effect’s code must be declared in your dependency list.

rickhanlonii avatar Feb 20 '24 19:02 rickhanlonii