We use hooks like useState()
instead of vanilla variables to store some state because we want the UI to update correctly. But isn’t that just a solution to the overcomplicated state created by React? Could we’ve gotten by updating the variables?
useState()
and useRef()
are meant for this purpose, so how are hooks more than that, and what do they solve?
2
Answers
No. Hooks are there for a reason. In your example
useState
saves a given state even though the component might be rendered multiple times and if states are changed, the component will update.Imagine the two functions:
When you click the button in
ComponentA
the component will not be updated. It will stay<p>0</p>
. It will not update the DOM.On the other hand,
ComponentB
will rerender the component.The second issue is the following; If
Parent
gets updated, thei
inComponentA
will be reset because it just does what the function instructs it to do so.On
ComponentB
, the state will be held in the background. So if you updateComponentB
it will keep the information.You obviously can still use normal variables though. E.g. when you have lists or simple calculations that don’t hurt performance that much:
But, as I explained those are the wrong choice for keeping some state.
You are right. useState() and useRef() might seem like a react-specific solution.
But,
if you see in vanilla js, you would have needed to write custom logic and update it. React, however, automatically re renders it and tracks those changes.
Without something like useState(), you would lose the previous state on every re-render because React components are re-executed each time they update.