useState Hook Implementation - State Management in JavaScript

useState Hook Implementation - State Management in JavaScript

Hooks in React

In React, a hook is a function that allows you to use state and other React features in functional components. Hooks were introduced in React 16.8 as a way to write reusable and stateful logic in functional components. In React we have several built-in Hooks like useState, useEffect, useContext, etc.

useState Hook Implementation

A simple implementation of the "useState" Hook in React:

Note: This will work for only one state, for more we need an array.

const React = (function () {
  let _val;
  function useState(initVal) {
    const state = _val || initVal;
    console.log("useState called");
    const setState = (newVal) => (_val = newVal); //setter function
    return [state, setState];
  }

  function render(Component) {
    const C = Component();
    C.render();
    return C;
  }
  return { useState, render };
})();

function Component() {
  const [index, setIndex] = React.useState(0);
  return {
    render: () => console.log("index: ", index),
    setIndex: () => setIndex(index + 1),
  };
}

let App = React.render(Component);
App.setIndex();
App = React.render(Component);
App.setIndex();
App = React.render(Component);
App.setIndex();
App = React.render(Component);
App.render();

Output

Explanation

  1. const React = (function () { ... })();: declares a constant named React and assigns it the result of an immediately invoked function expression (IIFE). The purpose of this IIFE is to create a closure and encapsulate the useState and render functions.

  2. Inside the IIFE, we have the following code:

    • let _val;: This line declares a variable _val in the function scope. It will be used as a private variable shared among components.

    • function useState(initVal) { ... }: This is the useState function implementation. It initializes the state variable with the current _val or the initVal passed as an argument. It also defines the setState function, which sets the _val to the new value provided. Finally, it returns an array containing the state and setState functions.

    • function render(Component) { ... }: This is the render function implementation. It takes a Component function as an argument. It invokes the Component function, which is expected to return an object with a render method. It calls C.render() to execute the render method of the Component and returns the Component object.

    • Finally, the IIFE returns an object containing the useState and render functions.

  3. function Component() { ... }: This is a sample component function that is meant to be rendered by the render function. It defines a useState call, which retrieves the state and setState functions from the React object. The Component function returns an object with a render method and a setIndex method. The render method logs the current index value to the console, and the setIndex method increments the index by 1.

  4. let App = React.render(Component);: This line calls the React.render function with the Component function as an argument. It assigns the returned value to the App variable. The App object should have a render method.

  5. App.setIndex();: This line calls the setIndex method on the App object, incrementing the index value by 1.

  6. App = React.render(Component);: This line re-renders the Component using the React.render function and assigns the new result to the App variable.

  7. Steps 5 and 6 are repeated multiple times to demonstrate how the state is preserved and updated across multiple renders.

_val forms a closure. A closure is a combination of a function and the lexical environment within which that function was declared. In this case, the useState function has access to the _val variable because it is declared in the outer function scope.

Each time the useState function is invoked, it references the same _val variable declared in the outer scope. This allows the state to be preserved between multiple invocations of the useState function and across different renders of the Component.

Hope you found this helpful.

Definitely you should checkout the video: https://www.youtube.com/watch?v=KJP1E-Y-xyo