Where State Lives
The course is part of this learning path
This module looks at how to identify state in a React application.
The objectives of this module are to provide you with an understanding of:
- How to identify state
- Where state lives
This learning path is aimed at all who wish to learn how to use the ReactJS framework.
Prerequisites of the Course
We welcome all feedback and suggestions - please contact us at firstname.lastname@example.org to let us know what you think.
The fourth part of Thinking In React is identifying where the state should live. Once we've identified data that should be stated in the application, we need to work out which components rely on the state, which can potentially mutate it, and which should own it. This might not be blatantly obvious when we look at our component hierarchy. Remember, react data flow is unidirectional, and data flows from the top of a component tree to the bottom. There is a three step process to identifying which component should own state. Firstly, identifying every component that renders something based on state. That means the component receives all, or part of, the state as props. Then, find a component higher up the tree than all the components that use the state, and put the state in this component. This could be an immediate owner component, or a component even higher up the tree. Lastly, if it doesn't make sense for the state to live in a common owning component, or one doesn't exist, create a new component to hold state and add it to the hierarchy at an appropriate place. It may be that two or more separate trees converge at this new component and it may only serve to provide a sensible place for state to live. There are other alternatives for managing where states live in an application, but they're for later in your React journey. So, continuing to follow our example. The Filterable Courses Table will receive the set of original courses as static data. That won't change and it passes these down to the course table as props. This, of course, is not state, but it's worth noting where the data comes from. Course Table needs to calculate the courses to pass as props to the course category row and the course row, based on the state values of search texts and the checkbox. Again, the courses passed down are not state, but they are calculated using two items from state. The search bar needs to display the search text and the checkbox value, as well as potentially mutate this data. The common owner component of course table and search bar is filterable courses table and it conceptually makes sense for search text and the checkbox value to live in the filterable courses table. We'll deal with how the search text and the checkbox value can mutate in the fifth, and final, part of the Thinking in React process. But before that, we need to know how to add state to a component, so make sure you check out our content on that.