Creating a Polyfill for useState in ReactJS: A Step-by-Step Guide
ReactJS Interview Secrets: How to Implement a useState Polyfill Like a Pro
These days, this question is a top choice for every interviewer who is taking an interview with a React Developer.
I will proceed with this article using the traditional interview style.
Interviewer: Do you know what useState is?
Me: Yes, useState is an inbuilt hook provided by React, which facilitates the capability of state management in a functional component by providing us a reactive variable and function to update the reactive variable.
Once we update this special reactive variable by the function provided by useState, if there is a difference b.w. previous and new value, then my component will be re-rendered with updated Value.
Interviewer: Nice. This is exactly how useState works. Now could you write a polyfill for it so that I can know if you know how it works internally, especially I want to check my understanding of custom hooks?
Me: Sure, here it might work.
Interviewer: Nice, but it does not trigger an update when you update the value. Could you please fix this?
Me: Sure, useState internally uses useReducer
to manage state updates, so we can leverage that as well, here is the link for that.
Interviewer: Good Job, but don’t you think this forced update will trigger on every state update?
Me: Oh Yes, I completely overlooked it, let me fix this.
Interviewer: Now that you have added this condition, this is a good time to discuss a bug that has been there since the beginning, could you please focus on initialValue = initialValue || value; and check if this can cause any potential issues?
Me: Well yes, I must say, you have an eye of eagle 🦅. So this will cause an issue. Basically what ||
does is, if the left side is falsey value (0,false,’’,undefined, null, NaN, -0, 0n) then right side value will be assigned.
In our case if newValue
is 0
, and oldValue
is 1
, in this case, newValue
will never get assigned. We can easily fix this by using ??
which will only assign the right side value in case the left side value is either null
or undefined
.
initialValue = initialValue ?? value;
Interviewer: Amazing, there is one more issue, this will not work when you have multiple useMyState
calls. Could you please address this?.
Me: Yes, Let’s do this.
Interviwer: Bravo !!! You Made it. 🙌, Before we close please tell me why you have used localHookId
why are you not using hookIdTracker directly?
Me: Thanks !! I’ve used localHookId
to freeze the value hookIdTracker
for each setter function or for each useState call.
Otherwise, each useMyState call will use the latest value of hookIdTracker
no matter in which order you call useMyState.
I hope this made you learn something. Do let me know in case I missed any edge cases here.