Interviewer: You’ve been React-ing for 5 years and missed useState?
useState: The Hook You Were Supposed to Know on Day 1
When I faced this question in an interview, it completely blew my mind.
The interviewer gave me this piece of react code and asked me to find the mistake.
The Code
function getDefaultScore() {
return 0;
}
function App() {
const [score, setScore] = useState(getDefaultScore());
const [count, setCount] = useState(0);
function increaseCount() {
setCount(count+1);
}
return <div>
<h1>Score is {score} </h1>
<h1> Count is {count} </h1>
<button onClick={increaseCount}>Increase Count</button>
</div>
}Now, when I saw the code first time, I was like it was correct, I don’t see any mistake here. I clearly told him that it looks good to me.
.
.
After that, the Interviewer asked me, Rahul can you tell me what are the different ways are by which we can initialize a state with a default value.
.
I quickly said, There is one way, just pass the value in useState.
.
After this, he smirked and said, Well there are 3 ways.
Pass the default value directly
Call a function that returns the value
Pass the function as a callback that returns the value.
Now, out of these three, 1 and 3 are safe. The issue is with 2 nd way.
When we call a function In useState, if any other state changes, React calls the function again. And this is the issue with above code.
.
The problem is that getDefaultScore runs every time the button is clicked — even when it’s not needed. If the function involves heavy computation, these unnecessary calls can negatively impact performance.
.
To summarise, here are the three ways to initialize the state.
function initialScore() {
console.log("score", 0);
return 0;
}
const [count, setCount] = useState(0);
const [score, setScore] = useState(initialScore);
const [defaultScore, setDefaultScore] = useState(initialScore()); // avoid at all cost