Skip to content
React logic · Senior · about 30 minutes

A tiny useState

Implement createHooks(). It returns { useState, render }. render(component) sets the hook cursor to 0, calls component(), remembers the component, and returns its result. useState(initial) returns [value, setValue] for the hook at the cursor and moves the cursor forward. State is stored by position, so the same order of calls gives the same state on every render. initial may be a function; it runs only for the first render. setValue takes a value or a function of the previous value; when the value changed (Object.is), it renders the component again, once. Each test names a scenario and shows what the component saw on every render.

Start from

function createHooks() {
  function useState(initial) {
    // Return [value, setValue] for the hook at the current position.
  }
  function render(component) {
    // Reset the position, call the component, return its result.
  }
  return { useState, render };
}

Hints and solution

Solve it in the app: its tests run without a year.

The hints, the solution and what an interviewer looks for opens with a year in the app. What a year includes