Importance of destructuring in react hooks
technikhil314
Posted on May 3, 2021
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);
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
.
.
.
.
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
.
.
.
.
What does this mean. It means following set of conclusions
- Any hook gets called during rerender too
- The return value of hook on each rerender is not referentially the same (except if you are returning primitive values from hook)
- Always destructure values from hook for sake of simplicity in the code.
- 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.
Posted on May 3, 2021
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.