react.dev
react.dev copied to clipboard
code example seems to have an extra dependency: onChange
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])
Hey @devmi 👋
I'm not sure I agree.
- In practice, the
onChangeprop may never change, but there's no way to guarantee that. - I think it would be more confusing to users to directly contradict the
useEffectdocumentation. - It raises an error to remove the dependency:
Thanks for the feedback though! ❤️
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.