A Closer Look at React 1: How useState Works and Closures

React Hooks and Closures

How does the useState hook manage state?

As the title suggests, it manages state through closures.

State management in function components

Unlike class components, which detect state changes through the render() method,

function components call the function itself when rendering occurs.

To manage state, they therefore need to remember the previous state when the function is called again.

How can they remember the previous state?

This is where closures come in.

  • A closure allows an inner function to access variables in its enclosing function’s scope.

Before looking at the actual implementation, I’ll try approaching it through code myself.

Here’s how I imagine useState is implemented.

const useState = (initialValue) => {
	let state = initialValue;
	const setState = (newValue) => {
		state = newValue;
	};

	return [state, setState];
};

const [counter, setCounter] = useState(0);

console.log(counter()); // 0
setCounter(1);

The problem is that state is a local variable within the function scope.

Even if setState changes state, we can’t observe that changed value outside the function. In other words, setState updates state, but the original state variable doesn’t reflect the new value.

To sum up, we haven’t implemented a closure function.

Because state is a variable, once useState returns it, that returned value can no longer change.

Improving it a little:

const useState = (initialValue) => {
	let state = initialValue;
	const setState = (newValue) => {
		state = newValue;
		return state;
	};

	state = setState(2);
	return [state, setState];
};
const [state, setState] = useState(0);

console.log(setState()); // 0
setState(1); //1

Now we can change the value through setState, which was the original problem.

But various problems still remain.

1. State immutability:

  • In React’s useState, the initial value (initialValue) stays unchanged even when state changes, and a new state value is returned for each change.
  • This code directly changes state every time state is set. That violates state immutability and can cause unexpected behavior.

2. The return value of setState:

  • In React, setState sets state and triggers a rerender, but returns no value.
  • Here, setState returns the new state value. This differs from React’s setState. Regardless of what setState returns, the existing state value stays the same after the call.

3. Calling setState immediately:

  • The state = setState(2); line inside useState calls setState immediately when useState runs, setting state to 2. This makes the initial value 0 meaningless: calling useState(0) always starts with 2.
  • React’s useState sets the initial state and doesn’t change it until setState is called.

4. Unconditional state changes in setState:

  • Here, calling setState changes state immediately. In React, setState triggers a rerender, and the new state is applied as the component renders again. This code has no rerendering logic, so even if state changes, that change isn’t immediately reflected.

Improving it a little further

Let’s move the closure inside another closure.

const MyReact = (function () {
	let value;
	return {
		render(Component) {
			const Comp = Component();
			Comp.render();
			return Comp;
		},
		useState(initialValue) {
			value = value || initialValue;
			function setState(newVal) {
				value = newVal;
			}
			return [value, setState];
		},
	};
})();

function Counter() {
	const [count, setCount] = MyReact.useState(0);
	return {
		click: () => setCount(count + 1),
		render: () => console.log("render:", { count }),
	};
}
let App;
App = MyReact.render(Counter); // render: { count: 0 }
App.click();
App = MyReact.render(Counter); // render: { count: 1 }

I built a small React clone using the module pattern.

It tracks component state, just like React.

Building useEffect

Unlike setState, useEffect runs asynchronously, making closure problems more likely.

function Counter() {
	const [count, setCount] = MyReact.useState(0);
	return {
		click: () => setCount(count + 1),
		render: () => console.log("render:", { count }),
	};
}
let App;
App = MyReact.render(Counter); // render: { count: 0 }
App.click();
App = MyReact.render(Counter); // render: { count: 1 }

useEffect and useState are both singletons here. Only one of each can exist; otherwise, bugs occur.

It’s not magic, just an array. To make closures work, we need to generalize this to handle any number of states and effects.

const MyReact = (function() {
  let hooks = [],
    currentHook = 0 // array of hooks, and an iterator!
  return {
    render(Component) {
      const Comp = Component() // run effects
      Comp.render()
      currentHook = 0 // reset for next render
      return Comp
    },
    useEffect(callback, depArray) {
      const hasNoDeps = !depArray
      const deps = hooks[currentHook] // type: array | undefined
      const hasChangedDeps = deps ? !depArray.every((el, i) => el === deps[i]) : true
      if (hasNoDeps || hasChangedDeps) {
        callback()
        hooks[currentHook] = depArray
      }
      currentHook++ // done with this hook
    },
    useState(initialValue) {
      hooks[currentHook] = hooks[currentHook] || initialValue // type: any
      const setStateHookIndex = currentHook // for setState's closure!
      const setState = newState => (hooks[setStateHookIndex] = newState)
      return [hooks[currentHook++], setState]
    }
  }
})()

setStateHookIndex may appear to do nothing, but it prevents us from closing over the wrong variable.

// Example 4 continued - in usage
function Counter() {
	const [count, setCount] = MyReact.useState(0);
	const [text, setText] = MyReact.useState("foo"); // 2nd state hook!
	MyReact.useEffect(() => {
		console.log("effect", count, text);
	}, [count, text]);
	return {
		click: () => setCount(count + 1),
		type: (txt) => setText(txt),
		noop: () => setCount(count),
		render: () => console.log("render", { count, text }),
	};
}
let App;
App = MyReact.render(Counter);
// effect 0 foo
// render {count: 0, text: 'foo'}
App.click();
App = MyReact.render(Counter);
// effect 1 foo
// render {count: 1, text: 'foo'}
App.type("bar");
App = MyReact.render(Counter);
// effect 1 bar
// render {count: 1, text: 'bar'}
App.noop();
App = MyReact.render(Counter);
// // no effect run
// render {count: 1, text: 'bar'}
App.click();
App = MyReact.render(Counter);
// effect 2 bar
// render {count: 2, text: 'bar'}

We now have an array and an index that increments with each hook call and resets whenever the component renders.

function Component() {
	const [text, setText] = useSplitURL("www.netlify.com");
	return {
		type: (txt) => setText(txt),
		render: () => console.log({ text }),
	};
}
function useSplitURL(str) {
	const [text, setText] = MyReact.useState(str);
	const masked = text.split(".");
	return [masked, setText];
}
let App;
App = MyReact.render(Component);
// { text: [ 'www', 'netlify', 'com' ] }
App.type("www.reactjs.org");
App = MyReact.render(Component);

Only Call Hooks at the Top Level

Don’t call hooks inside loops, conditions, or nested functions.

State is stored in an array in the component’s execution order.

Why should hooks only be called at the top level?

Don’t call hooks from ordinary JavaScript functions.

Call them only inside React function components or custom hooks.

Why should hooks only be called from React functions?

→ Following these two rules ensures hooks are called in the same order every time the component renders.

// ReactHooks.js

export function useState<S>(
	initialState: (() => S) | S
): [S, Dispatch<BasicStateAction<S>>] {
	const dispatcher = resolveDispatcher();
	return dispatcher.useState(initialState);
}

This is the initial useState implementation I found in the React module.

Assign resolveDispatcher’s return value to dispatcher.

Then pass initialState to the dispatcher’s useState method.

function resolveDispatcher() {
	const dispatcher = ReactCurrentDispatcher.current;

	if (__DEV__) {
		if (dispatcher === null) {
			console.error("Some error msg...");
		}
	}

	return ((dispatcher: any): Dispatcher);
}

resolveDispatcher reads the current value of ReactCurrentDispatcher.

const ReactCurrentDispatcher = {
	/**
	 * @internal
	 * @type {ReactComponent}
	 */
	current: (null: null | Dispatcher),
};

ReactCurrentDispatcher.current is a property on a globally declared object.

The key point is that the source of useState’s return value is global.

We can see that React really uses closures to access values outside a function.

Why use setState(prev → prev + 1)?

const Counter = () => {
	const [count, setCount] = useState(0);

	const increase1 = () => {
		setCount(count + 1);
		setCount(count + 1);
		setCount(count + 1); //1
	};

	const increase2 = () => {
		setCount((count) => count + 1);
		setCount((count) => count + 1);
		setCount((count) => count + 1); //3
	};
};

export default Counter;

The difference is whether the argument to setState is a value or a function.

If the new state is computed using the previous state, you can pass a function to setState.

When new state needs to be calculated from the immediately preceding state, use a function.

That’s because React uses a special batching process to improve performance.

It groups multiple setState updates, processes them together, and determines state from the final result.

Looking at useState’s internal structure helps explain why a functional argument updates the value as it goes.

The internal useState structure: what you see when you assign an actual hook to a variable and print it.

next forms a linked list, connecting multiple hooks executed within one component.

{
  memoizedState: 0, // first hook
  baseState: 0,
  queue: { /* ... */ },
  baseUpdate: null,
  next: { // second hook
    memoizedState: false,
    baseState: false,
    queue: { /* ... */ },
    baseUpdate: null,
    next: { // third hook
      memoizedState: {
        tag: 192,
        create: () => {},
        destory: undefined,
        deps: [0, false],
        next: { /* ... */ }
      },
      baseState: null,
      queue: null,
      baseUpdate: null,
      next: null
    }
  }
}

References

How React useState Works and Closures

https://www.netlify.com/blog/2019/03/11/deep-dive-how-do-react-hooks-really-work/

https://seokzin.tistory.com/entry/JavaScript-%EC%8B%A4%ED%96%89-%EC%BB%A8%ED%85%8D%EC%8A%A4%ED%8A%B8-Execution-Context#%25F-%25-F%25—%25-E%25—%ED%25—%25B-%EB%25A-%25-C%EC%25A-%25—%25---Closure-