Let’s clear up uncertainty about where to declare state in React apps
The purpose of state in React is an easy way to track fields on a website whose values can change over time. What does that look like in practice? Imagine you are shopping online at your favorite store for a new t-shirt. As you type in the brand name, the search form that offers suggestions for what you might be looking for. Another example, when the t-shirt results arean ecommerce site that filters 4k televisions by price and rating, then allows you to click a box to filter those with free shipping
I am creating a fun app to display the characters from the animated show, “Rick and Morty.” It displays a character’s avatar and stats on a card, and allows a user to click on a character card to add it to a favorites list. To start, I would want to declare the state of the list of all characters, so that it can be loaded to the page. Taking the React lifecycle into account, I would set my state of allCharacters to a blank array and would pass that down as a prop to the child components in order to display the cards.
I would like the character card to have the character avatar for the frontview and the character details and an add button for the backview. In order to , I would add state directly to each card, since that is the only component that would ever use it.
In the above examples, state is updated dynamically causing a re-rendering of the DOM. More specifically, changing the state will automatically trigger a re-render of the DOM in order to show that the Rick character has been removed from the main container and added to my favorites container.
If you are still confused about state where to put state, the React Documentation has some great tutorials. Here are my favorite tips:
1. Map out your component tree
2. Determine which items will need access to state
3. Find their common ancestor
4. That is where your state lives
As you start to add behavior, remember that any function that needs to alter the state should be housed in this parent component, as well. At that point, remember to pass any callbacks to update state as a prop.