Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

> e.g. I'm not sure how they're implemented

It might help to have a simple mental model for them?

Picture there is a global variable called _currentComponent:

  _currentComponent: {
    previousValue: React.Element
    hooks: HookValue[]
    currentHook: number
    firstRender: boolean
  }
Each HookValue is whatever that hook wants. For useState something like:

  HookValue = {
    hookName: 'useState',
    value: [state, setState],
  }
Before your component is run, the renderer sets `_currentComponent` to your component with its hooks set to their current values.

If you run `useState(initial)` it looks like this:

  function useState(initialValue) {
    const component = _currentComponent
    let hookValue;
    if (firstRender) {
      hookValue = {
        hookName: 'useState',
        value: [initialValue, (newValue) => {
          hookValue[0] = newValue
          markForUpdate(component); // some React-provided function to mark this as needing an update
        }
      }
      component.hooks[component.currentHook++] = hookValue;
      return hookValue.value
    } else {
      hookValue = component.hooks[component.currentHook++]
      assert(hookValue.hookName == 'useState')
      return hookValue.value
  }
Surely not perfect, but totally useable as a model of what's going on. To be honest I wish React showed pseudocode like this in the tutorials, it makes it a lot easier for me to understand.


Yep! Also see Shawn Swyx Wang's talk "Getting Closure on React Hooks", where he goes through an equivalent example in more detail:

https://www.swyx.io/hooks/


Thank you for posting this.




Consider applying for YC's Fall 2026 batch! Applications are open till July 27.

Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: