Lesson 4. What are hooks anyway? 2. How React renders a component with a local state
In this variant, the name is no longer a prop, but a local state, updated with
an input:
const WithLocalState = () => {const [name, setName] = useState('John')return (<><input value={name} onChange={(event) => setName(event.target.value)} /><p>Hello {name}!</p></>)}
When React encounters the call to useState, it initializes a local state
somewhere in the memory, knowing that it is linked to the first hook call in
this component.
// Rendering 1const [name, setName] = useState('John')// → HOOKS[0] := [state: 'John']return <> ...Hello John... </>
The subsequent renderings of this component will assume that the first call to
useState always refers to this first memory index (HOOKS[0] in our
representation).
When the state value is updated by a call to setName, a second rendering is
triggered:
// setName('Jane')// → HOOKS[0] := [state: 'Jane']// ↓// Rendering 2const [name, setName] = useState('John')// → HOOKS[0] already exists, returns 'Jane'return <> ...Hello Jane... </>
Notice that since it is not the first rendering anymore, React ignores the
initial state value 'John' we provided as a parameter to useState.
The behavior would be the same with several states, just with several state
elements in our imaginary array HOOKS.
Now let’s see what happens when we introduce a call to useEffect.