React Hooks under the hood

How do React Hooks work under the hood? With React Hooks, instead of worrying about bound context (class, this…), we get confused by Closure!

Deep dive: How do React Hooks work under the hood?

React 16.8 introduced Hooks, a new approach to managing state and side effects more effectively. The idea behind React Hooks was quickly and positively embraced by the JavaScript community, for example by Vue, Svelte, and even VanillaJS. However, the way Hooks are designed requires a deep understanding of Closure in JavaScript.

This post explains closure in a simple way by cloning a simple version of “React Hooks”.

Closure: helps work with state in JavaScript

State in programming languages simply means holding on to values.

For example:

let a = 0;

a = a + 1; // =>~~~~ 1
a = a + 1; // => 2
a = a + 1; // => 3

In the example above, the state is held in the variable a. To control how an object changes, we have to record its state. What holds the state in the example above is the variable a, which keeps the state in memory.

When programming, you usually want to keep track of things, remember the state of objects, and access it later. In popular OOP languages (JS with ES6+), this is done with the concepts of class and instance, for example:

class Bread {
  constructor(weight) {
    this.weight = weight;
  }

  render() {
    return `My weight is ${this.weight}!`;
  }
}

However, in JavaScript (which didn’t support Classes from the start!) and in languages that only support functional programming (like Elixir, Lisp), we can use Closure as an effective and optimal way to manage state.

For example:

let n = 0;
const count = function() {
  n = n + 1;
  return n;
};

count(); // 1
count(); // 2
count(); // 3

The example above stores state in the global variable n, but this isn’t very safe since n is exposed and any other function can change its value. We can do better with a simple closure that encapsulates the state in a function:

const countGenerator = function() {
  let n = 0;
  const count = function() {
    n = n + 1;
    return n;
  };

  return count;
};

const count = countGenerator();
count(); // 1
count(); // 2
count(); // 3

So pro! 😃 In functional programming, where functions are first-class citizens, we can work with state and side effects without needing things like classes, methods, or instances.

What is Closure?

One of the advantages of Hooks in React is less complexity, and getting rid of the headache-inducing, hard-to-reuse side effects caused by class and higher order component. But Hooks bring another problem to watch out for. Instead of worrying about bound context (class, this…), we get confused by Closure:

Closure

Closure is one of the core concepts of JavaScript and other languages that support functional programming (like Elixir, Lisp, or even Ruby), yet it’s still a nightmare for many developers starting out. Kyle Simpson, in You Don’t Know JS, defines Closure as follows:

“Closure is when a function is able to remember and access its lexical scope even when that function is executing outside its lexical scope.”

or

“Closures are functions that refer to independent (free) variables. In other words, the function defined in the closure ‘remembers’ the environment (lexical environment) in which it was created.”

To make it easier to understand, let’s clone React Hooks’ useState function using closure:

// Example 0
function useState(initialValue) {
  let _val = initialValue; // _val is a local variable created by useState
  function state() {
    // state is an inner function of the parent useState, a closure
    return _val; // state() uses _val, declared by the parent function
  }
  function setState(newVal) {
    _val = newVal; // assign _val without exposing _val
  }
  return [state, setState]; // expose the functions to be called from outside
}

const [foo, setFoo] = useState(0); // use array destructuring
console.log(foo()); // logs 0 - the initial value
setFoo(1); // assign _val inside the scope of useState
console.log(foo()); // logs 1 - the new value

Done, we’ve finished cloning React Hooks’ useState function. It returns 2 inner functions, state and setState. state returns the local variable _val declared above, and setState assigns that local variable the value passed in (newVal). With foo and setFoo we can work with a local variable (a state).

Using useState in Functional Components

Let’s try simulating the newly created useState function inside a Function Component, for example a Counter Component:

// Example 1
function Counter() {
  const [count, setCount] = useState(0); // use the useState function we just created
  return {
    click: () => setCount(count() + 1),
    render: () => console.log("render:", { count: count() }),
  };
}
const C = Counter();
C.render(); // render: { count: 0 }
C.click();
C.render(); // render: { count: 1 }

Here we’re not outputting to the DOM, only printing with console.log, but this simulation is enough to understand how useState is used in a React Component.

Still, this function isn’t 100% compatible with the real React.useState API, because count is still a function instead of a variable.

Improving useState to match the React.useState API

Turning count into a variable instead of a function isn’t easy either. If we simply expose _val instead of wrapping it in a function, we get a bug right away:

// Example 1, this function has a BUG!
function useState(initialValue) {
  let _val = initialValue;
  // no more state() function
  function setState(newVal) {
    _val = newVal;
  }
  return [_val, setState]; // expose _val directly
}
const [foo, setFoo] = useState(0);
console.log(foo); // logs 0 without calling a function
setFoo(1); // assign _val in the scope of useState
console.log(foo); // still logs 0 - what a damn bug!!

This is a Stale Closure problem. When we destructure foo from useState, it will always be the initial value of useState and never return the current value.

Improving Closure with the Module Pattern

We can solve the problem above by… moving a closure into another closure. 😃😃😃?😃😃😃

// Example 2
const MyReact = (function() {
  let _val; // keep state in module scope
  return {
    render(Component) {
      const Comp = Component();
      Comp.render();
      return Comp;
    },
    useState(initialValue) {
      _val = _val || initialValue; // reassign the new value after each run
      function setState(newVal) {
        _val = newVal;
      }
      return [_val, setState];
    },
  };
})();

As written above, we used the Module pattern to create a useState function compatible with the React API. This lets MyReact “render” a function component and reassign the local variable _val each time, with a proper closure:

// Example 2.1
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 }

You can read more about the Module Pattern and Closure in You Don’t Know JS.

Continuing with a useEffect clone

After useState, the most basic React Hook, useEffect is another pretty important React Hooks API (it replaces React Class Component lifecycles like ComponentDidMount or ComponentDidUpdate…). Unlike useState, useEffect runs asynchronously, which means it’s more bug-prone (facing closure problems).

We can extend MyReact above to implement a clone of useEffect:

// Example 3
const MyReact = (function() {
  let _val, _deps; // keep state and dependencies in scope
  return {
    render(Component) {
      const Comp = Component();
      Comp.render();
      return Comp;
    },
    useEffect(callback, depArray) {
      const hasNoDeps = !depArray;
      const hasChangedDeps = _deps ? !depArray.every((el, i) => el === _deps[i]) : true;
      if (hasNoDeps || hasChangedDeps) {
        callback();
        _deps = depArray;
      }
    },
    useState(initialValue) {
      _val = _val || initialValue;
      function setState(newVal) {
        _val = newVal;
      }
      return [_val, setState];
    },
  };
})();

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

To track the dependencies (since useEffect reruns whenever one of its dependencies changes), we use another variable to keep track: _deps.

Using a Hooks Array

The useState and useEffect clones above work almost fine functionally, but we run into trouble when using both at the same time (only one of them can exist, or there will be bugs). To solve this, we use a hooks array, as Rudi Yardley wrote: React Hooks: not magic, just arrays 😃. We can fold _val and _deps into the hooks array since they never collide:

// Example 4
const MyReact = (function() {
  let hooks = [],
    currentHook = 0; // hooks array
  return {
    render(Component) {
      const Comp = Component(); // run effects
      Comp.render();
      currentHook = 0; // reset for the 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++;
    },
    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];
    },
  };
})();

In short: there’s an array of hooks and an index (currentHook) that increments each time a hook is called, and resets whenever the component re-renders.

Where the rules of React Hooks come from

From the clone implementation above you can get a rough idea of one of the rules of using React Hooks: only call Hooks at the Top Level. We’ve clearly modeled React’s dependence on call order with the currentHook variable above. You can read more about this rule on the React docs site.

References