What is it and why should I provide a "dependency array" for React’s Hooks?

Asked

Viewed 65 times

2

Who has never forgotten to pass a "dependency" to the dependency array Hooks react?

It’s an unfortunate burden that every person using React has to be aware of: passing the right dependency to the effect or hook that requires it. They even created a plugin to the Eslint to facilitate this. Passes an aura of Leaky abstraction, but that’s beside the point.

  • What is this "dependency array"?
  • Why is it necessary in this kind of hook? Why does React demand it?
  • How React uses the values I pass in the array in question?

1 answer

-1

Let me give you a basic example:

const MeuComponente = () => {
  const [counter, setCounter] = useState(0);

  const incrementCounter = useCallback(()=>{
     setCounter(counter + 1);
  },[])

  return (
     <h1>{counter}</h1>
     <button type="button" onClick={()=> incrementCounter()}>Incrementar</button>

  )

}

export default MeuComponente;


In the above form without an array of dependencies, at the time React creates the function incrementCounter the value of counter is 0.

Then when calling it at the click of the button, it is made the set of a new value being passed (counter + 1). Note that this counter vale 0, then the new value for counter sera 1.

But in the next clicks on the button when calling the increment function, the value of the counter variable inside remains 0, because this function was only created once with the use of useCallback, and the value contained in it is still that the counter was 0.

That is, from this no matter how many clicks you give on the button the counter value will always be displayed as 1, but within the function it is still 0.

This means that the counter value has not been updated inside the function.

To make the value inside be updated and reflect the real value, it is necessary to include it in the dependency array.

This causes the function to be updated and the values contained inside to be updated based on this dependency array.

const MeuComponente = () => {
  const [counter, setCounter] = useState(0);

  const incrementCounter = useCallback(()=>{
     setCounter(counter + 1);
  },[counter])

  return (
     <h1>{counter}</h1>
     <button type="button" onClick={()=> incrementCounter()}>Incrementar</button>

  )

}

export default MeuComponente;


Of course it is just an example, the ideal would be to do setCounter(Prev=> Prev + 1), this would avoid having to pass dependencies to useCallback.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.