When writing React applications, it’s important to know when and when not to use state in components. In this post, I will review what I consider to be best practices for working with state. TL;DR:
- If a component does not own a datum, then that datum should not influence it’s state.
- Store the simplest possible values to describe a component’s state.
- Leave calculations and conditionals to the render function.
These rules obviously have exceptions and should be violated when appropriate; though if you’re able to follow them most of the time, you will find that your components will be easier to break down, the tests will be easier to write, and the entire application will have fewer bugs. Let’s take a closer look at each of these rules.