https://javascript.plainenglish.io/why-you-shouldnt-always-use-usestate-658994693018
Hello, I am a front-end developer and I want to share my opinion regarding why you shouldn’t always use useState
.
TL;DR: useStateis an asynchronous hook and it doesn’t change the state immediately, it has to wait for the component to re-render.
useRef
is a synchronous hook that updates the state immediately and persists its value through the component’s lifecycle, but it doesn’t trigger a re-render.
Recently, I was pair-programming with a co-worker who was struggling with a “weird bug”.
To put things into context, I made this example.
My tender-hearted friend was confused why his form wasn’t submitting the input correctly as expected.
I suggested that he use a “normal variable” instead of useState
, but he looked down on me as if I was just an idiot (how did he know?😅) and jokingly said: “You obviously don’t know what you are speaking about.”
To his own surprise, the variable came in handy.
Okay, I just want to declare that you shouldn’t always rely on useRef
or a “normal variable” for all cases, but I just want to share why sometimes I would prefer them over useState
.
Look at the example below.
Do you know what is going to happen?
useState
is an asynchronous hook, it will wait for the component to finish its cycle, re-render, and then it will update the state. Thus, userToken
line 20 is still an empty string.