I'm having a hard time understanding the 'exhaustive-deps' lint rule.
I already read this post and this post but I could not find an answer.
Here is a simple React component with the lint issue:
const MyCustomComponent = ({onChange}) => {
const [value, setValue] = useState('');
useEffect(() => {
onChange(value);
}, [value]);
return (
<input
value={value}
type='text'
onChange={(event) => setValue(event.target.value)}>
</input>
)
}
It requires me to add onChange to the useEffect dependencies array. But in my understanding onChange will never change, so it should not be there.
Usually I manage it like this:
const MyCustomComponent = ({onChange}) => {
const [value, setValue] = useState('');
const handleChange = (event) => {
setValue(event.target.value);
onChange(event.target.value)
}
return (
<input
value={value}
type='text'
onChange={handleChange}>
</input>
)
}
Why the lint? Any clear explanation about the lint rule for the first example?
Or should I not be using useEffect here? (I'm a noob with hooks)
useEffectis very similar to a combination ofcomponentWillMount,componentDidMount, and when you return a function fromuseEffectthat function is treated ascomponentWillUnmount. All you're handling at the moment is a simple state change and theuseStatehook is enough to accomplish thatuseEffectdoesn't seem appropriate. The proponChangecan easily be moved to the body of theonChangemethod of theinput. Although it should be renamed for clarity. Basically the second example OP gave in the question.useEffectcould benefit from an additionaltriggersparameter.