DEV Community

loading...
Cover image for Importance of destructuring in react hooks

Importance of destructuring in react hooks

technikhil314 profile image technikhil314 ・2 min read

Have you realized that we are using destructuring every where with react hooks. Take a look at this simple example

const [counter, setCounter] = useState(0);
Enter fullscreen mode Exit fullscreen mode

We are using destructuring here, to get statevalue and state updater function. But why does it have to be this way always.

well here is my take on explaining why destructuring is important. Take a look at this sandbox. Its a simple counter component that updates every second.

If you check the logs on the console. They will be something like this

counter updated new value is 0 
setCounter  updated 
counter updated new value is 1 
counter updated new value is 2 
counter updated new value is 3 
counter updated new value is 4 
counter updated new value is 5 
.
.
.
.
Enter fullscreen mode Exit fullscreen mode

Now suppose we don't use destructuring for useState hook and accept it as array in which state[0] is our counter value and state[1] is counter updater function. Check the sandbox

and check the logs on console too

counter updated new value is 0 
setCounter  updated 
counter updated new value is 1 
setCounter  updated 
counter updated new value is 2 
setCounter  updated 
counter updated new value is 3 
setCounter  updated 
counter updated new value is 4 
setCounter  updated
.
.
.
.
Enter fullscreen mode Exit fullscreen mode

What does this mean. It means following set of conclusions

  1. Any hook gets called during rerender too
  2. The return value of hook on each rerender is not referentially the same (except if you are returning primitive values from hook)
  3. Always destructure values from hook for sake of simplicity in the code.
  4. useEffect dependancy are shallow checked for equality.

I hope you like or understood what I am trying to explain here. If you have any suggestion please comment it down below.

Discussion (0)

pic
Editor guide