3 ms·
If the dependency array lint rule is yelling at you there's a very, very good chance your component is broken. As an example I used to see class components like
by ng12 6y ago
If the dependency array lint rule is yelling at you there's a very, very good chance your component is broken. As an example I used to see class components like this all the time:
class Foo extends React.Component {
componentDidMount() {
fetchFoo(this.props.id)
.then(foo => this.setState({foo}))
}
render() { ... }
}
This component is fundamentally broken because there is no `componentDidUpdate` to re-call `fetchFoo` when `this.props.id` changes. I could easily be rendering a new id with an old id's foo. The developer is making an assumption that the initial value of `id` will never change, therefore making assumptions about how the parent component is instantiating `Foo`. Rewriting this using hooks makes this immediately obvious:
const Foo = ({id}) => {
const [foo, setFoo] = React.useState(null)
React.useEfect(() => {
fetchFoo(id).then(setFoo)
, []) // Linter complains, and it should!
return ...
}
There's nothing wrong with using the empty array as your deps so long as it's actually what you want to do. If `fetchFoo()` didn't require any arguments and we only wanted to invoke it once [] would absolutely be the right dependency array. There are few cases I can think of where disabling the linter check is correct. The most common occurence in my code is if the effect uses a value not required to be fresh: e.g. something used for an optimization.