React Best Practices

Chapter 2 of 8 · 5 practices · 4 min · 4-question quiz

State and data flow

Where state should live, how much of it you need, and how to update it so React notices. Most re-render bugs start here.

Start: Keep state minimal and derive everything else during render

5 practices in this chapter

  1. 1Keep state minimal and derive everything else during renderEvery extra piece of state is something you have to keep in sync, and sooner or later stored copies drift apart. If a value can be calculated from props or other state, do not store it.
  2. 2Keep state as close as possible to where it is usedState placed too high in the tree makes every component below it re-render on each change, and makes the data flow harder to follow.
  3. 3Update objects and arrays immutablyReact decides whether to re-render by comparing old and new state with Object.is. If you mutate an object or array in place and pass the same reference to the setter, React may skip the update, and…
  4. 4Reset a component's state by changing its keySometimes a component should start fresh for a new item, such as a comment box when you switch to another user's profile. Give it a key tied to that item.
  5. 5Use a reducer when several state values change togetherWhen one user action updates three pieces of state, or the next state depends on several current values, scattered useState calls get hard to reason about.

Check yourself on this chapter

4 questions, right here once you are signed in. Your progress is saved as you read.

Sign up for the quiz