the React Hooks mental model

notes from Fun with React Hooks - Michael Jackson and Ryan Florence

the ryan florence part of the talk

##but first, go and watch it! i'll wait.

here are some key takeaways

ryan florence built a mental model of useState to bring us through how to reason about hooks and to understand some of the quirky 'rules of hooks'

the code

this is useState as a mental model, not the full react hooks useState it is still runnable, but won't register the right states for more than one component as it has no logic to listen to react's mount and unmounts

const states = []
let calls = -1

// works similarly as React's official hooks implementation (with caveats as stated above)
const useState = defaultValue => {
  const callId = ++calls

  if (states[callId]) {
    return states[callId]
  }

  const setValue = newValue => {
    states[callId] = newValue // assigns new value to state
    renderWithCrappyHooks() // trigger a rerender
  }

  const tuple = [defaultValue, setValue]
  states[callId] = tuple // update states with the latest tuple
  return tuple
}

function renderWithCrappyHooks() {
  calls = -1 // reset state tracking before rerendering to make sure the
  ReactDOM.render(<App />, document.getElementById('root'))
}
renderWithCrappyHooks() // initial render

end remarks from ryan florence