Writing React from Scratch or Why React Hooks make sense

·

2 min read

I have recently watched the talk "Getting Closure on React Hooks" presented by Shawn "Swyx" Wang at JSConf.Asia 2019 and I found it to be interesting, enlightening and fun! I got to follow and code along a minimalist implementation of React and the useState and useEffect Hooks.

React also explains in its documentation how the useState and the useEffect hooks are implemented, but the live coding from Swyx brought my understanding to a deeper level.

My main takeaways from the talk and the documentation are:

  1. Power to simple technical concepts such as closure and index-based state mapping.

  2. React manages state for function components in arrays.

  3. The order in which hooks are called matters. The same order must be kept.

    For every component, React holds an array where state is stored. The order in which these states are stored corresponds to the order of useState calls inside the component. Each state is thus retrieved based on the index corresponding to the call order. With each rendering of the component, the index is reset to 0 and incremented with each useState call.
  4. React detects changes in the useEffect dependency array by comparing the previous dependencies with the current dependencies with Object.is().

  5. Because of the way React implements hooks, the hook rules make more sense now. Conditionally calling an useState hook would mess up the state - useState stable mapping.