Add state to an application
React manages state in a few ways. We'll focus on one of the main ways, React Hooks.
A Hook is a mechanism that allows you to access the inner workings of React. You can use Hooks to run code when something changes in React. Or use them to register something with React, such as state. When we create state by using the useState
Hook, for example, we get the state object and an updater function to update the Hook value.
Scenario
One common technique many cooks use is mise en place, which is from the French "putting in place." Cooks ensure all items are prepared before they begin cooking.
In our recipe application, we want to allow users to tap ingredients to mark them as prepared. We'll start by creating the state and passing the display information to the component. In the next unit, we'll explore how to handle events.
Add state
Any JavaScript object or data type can be registered as stateful in React. The function used to register the object is useState
. The useState
function specifies the initial value. It returns the newly created stateful object and another function you can use to update the value.
Note
In React, state is immutable, meaning it can't be changed. To modify the value of a stateful object, replace it with a new instance that contains the appropriate values. The function returned by useState
manages this process.
In VS Code Explorer, expand the src folder, and then open the App.jsx file. Notice the existing
initialRecipe
object. We'll use this object as the default value for our statefulrecipe
.Create the
recipe
state object andsetRecipe
function fromuseState
. To do so, add the following code after the line that reads,TODO: Create recipe state
.const [ recipe, setRecipe ] = useState(initialRecipe);
In this code,
recipe
is the stateful object. ThesetRecipe
function will be used to replacerecipe
with any new versions.We can use
recipe
to pass props into components. In the following code, theRecipeTitle
component will be used to display the title and feedback. Pass thetitle
andfeedback
values intoRecipeTitle
by adding the following code after the comment that reads,TODO: Pass recipe metadata to RecipeTitle
.<RecipeTitle title={recipe.title} feedback={recipe.feedback} />
Open the RecipeTitle.jsx file. Notice the existing component that displays
title
andfeedback
props.
Test the page
Save all of the files.
Return to your browser and refresh it. You should now see the recipe metadata displayed on the page.