If you prefer video over text. Here’s a video i made a few weeks back.

The useState hook is probably the most used hook in React. For those who don’t remember, here’s a quick refresher.

const [count,setCount] = useState(0)
         |      |                 |
       value  mutation       initial value

The useState hook is a function that returns, a value and a function to mutate that value. An initial value can be passed as parameter to the useState function.

So if you dumb it down, useState is basically a “stateful” function. Stateful here means, the variable value is persisted across multiple re-runs of the function.

With that knowledge, let’s start our journey of writing useState hook for scratch. We will first try to build a naive solution and then build on that.

Super Naive.

let count = 0;
function addCount() {
	count = count + 1;
}

addCount();
console.log(count) //1
addCount();
console.log(count) //2

Like i said, pretty naive solution. Declaring state in global scope is pretty bad. Any other piece of code can change it and break our component “state”. Also we haven’t figured out how to set the initial state

We can do better.

const React = (function(){
  function useState(initVal) {
    let count = initVal;
  	function setCount() {
   		count = count + 1;
 		}
		return [count, setCount] 
  }
  return {useState}
})()

let [num, setNum] = React.useState(0);
console.log(num) //0
setNum()
console.log(num) //0 ????

This might seem overwhelming so let me break it down.

Dry run

On calling the useState hook, the count variable is set to initial value ie.0 and that can be verified by the output of the 1st console.log statement.