How React decides what to re-render
Keys, dependency arrays and when an effect is the right tool.
11 min read
React's rendering model is small. Three details account for most of the confusion.
Keys identify items across renders. A key tells React which element in the new list corresponds to which in the previous one, so that state remains attached to the correct row. An array index works until the list is reordered or an item is removed, at which point state follows position rather than content.
The dependency array determines when an effect runs. No array means after every render; an empty array means once, after mount; an array of values means after any render in which one of them changed. An incorrect array produces either a request loop or a view that never updates, and both resemble a backend fault.
Most effects are unnecessary. Before writing one, establish which case applies: synchronising with something outside React, such as a subscription or the document title, calls for an effect; deriving a value from props or state should be computed during render; responding to a click belongs in the handler.
State updates are asynchronous within a handler. Reading state immediately after setting it returns the previous value. Where the next value depends on the previous one, use the function form.
Go deeper
Lessons are not assessed. Progress towards the certificate is recorded from the work you submit. See all requirements