One place for hosting & domains

      How To Share State Across React Components with Context


      The author selected Creative Commons to receive a donation as part of the Write for DOnations program.

      Introduction

      In this tutorial, you’ll share state across multiple components using React context. React context is an interface for sharing information with other components without explicitly passing the data as props. This means that you can share information between a parent component and a deeply nested child component, or store site-wide data in a single place and access them anywhere in the application. You can even update data from nested components by providing update functions along with the data.

      React context is flexible enough to use as a centralized state management system for your project, or you can scope it to smaller sections of your application. With context, you can share data across the application without any additional third-party tools and with a small amount of configuration. This provides a lighter weight alternative to tools like Redux, which can help with larger applications but may require too much setup for medium-sized projects.

      Throughout this tutorial, you’ll use context to build an application that use common data sets across different components. To illustrate this, you’ll create a website where users can build custom salads. The website will use context to store customer information, favorite items, and custom salads. You’ll then access that data and update it throughout the application without passing the data via props. By the end of this tutorial, you’ll learn how to use context to store data at different levels of the project and how to access and update the data in nested components.

      Prerequisites

      Step 1 — Building the Basis for Your Application

      In this step, you’ll build the general structure of your custom salad builder. You’ll create components to display possible toppings, a list of selected toppings, and customer information. As you build the application with static data, you’ll find how different pieces of information are used in a variety of components and how to identify pieces of data that would be helpful in a context.

      Here’s an example of the application you will build:

      Salad Builder Site

      Notice how there is information that you might need to use across components. For example, the username (which for this sample is Kwame) displays user data in a navigation area, but you may also need user information to identify favorite items or for a checkout page. The user information will need to be accessible by any component in the application. Looking at the salad builder itself, each salad ingredient will need to be able to update the Your Salad list at the bottom of the screen, so you’ll need to store and update that data from a location that is accessible to each component as well.

      Start by hard-coding all the data so that you can work out the structure of your app. Later, you’ll add in the context starting in the next step. Context provides the most value as applications start to grow, so in this step you’ll build several components to show how context works across a component tree. For smaller components or libraries, you can often use wrapping components and lower level state management techniques, like React Hooks and class-based management.

      Since you are building a small app with multiple components, install JSS to make sure there won’t be any class name conflicts and so that you can add styles in the same file as a component. For more on JSS, see Styling React Components.

      Run the following command:

      npm will install the component, and when it completes you’ll see a message like this:

      Output

      + react-jss@10.3.0 added 27 packages from 10 contributors, removed 10 packages andaudited 1973 packages in 15.507s

      Now that you have JSS installed, consider the different components you’ll need. At the top of the page, you’ll have a Navigation component to store the welcome message. The next component will be the SaladMaker itself. This will hold the title along with the builder and the Your Salad list at the bottom. The section with ingredients will be a separate component called the SaladBuilder, nested inside SaladMaker. Each ingredient will be an instance of a SaladItem component. Finally, the bottom list will be a component called SaladSummary.

      Note: The components do not need to be divided this way. As you work on your applications, your structure will change and evolve as you add more functionality. This example is meant to give you a structure to explore how context affects different components in the tree.

      Now that you have an idea of the components you’ll need, make a directory for each one:

      • mkdir src/components/Navigation
      • mkdir src/components/SaladMaker
      • mkdir src/components/SaladItem
      • mkdir src/components/SaladBuilder
      • mkdir src/components/SaladSummary

      Next, build the components from the top down starting with Navigation. First, open the component file in a text editor:

      • nano src/components/Navigation/Navigation.js

      Create a component called Navigation and add some styling to give the Navigation a border and padding:

      [state-context-tutorial/src/components/Navigation/Navigation.js]
      import React from 'react';
      import { createUseStyles } from 'react-jss';
      
      const useStyles = createUseStyles({
        wrapper: {
          borderBottom: 'black solid 1px',
          padding: [15, 10],
          textAlign: 'right',
        }
      });
      
      export default function Navigation() {
        const classes = useStyles();
        return(
          <div className={classes.wrapper}>
            Welcome, Kwame
          </div>
        )
      }
      

      Since you are using JSS, you can create style objects directly in the component rather than a CSS file. The wrapper div will have a padding, a solid black border, and align the text to the right with textAlign.

      Save and close the file. Next, open App.js, which is the root of the project:

      • nano src/components/App/App.js

      Import the Navigation component and render it inside empty tags by adding the highlighted lines:

      state-context-tutorial/src/components/App/App.js

      import React from 'react';
      import Navigation from '../Navigation/Navigation';
      
      function App() {
        return (
          <>
            <Navigation />
          </>
        );
      }
      
      export default App;
      

      Save and close the file. When you do, the browser will refresh and you’ll see the navigation bar:

      Navigation Bar

      Think of the navigation bar as a global component, since in this example it’s serving as a template component that will be reused on every page.

      The next component will be the SaladMaker itself. This is a component that will only render on certain pages or in certain states.

      Open SaladMaker.js in your text editor:

      • nano src/components/SaladMaker/SaladMaker.js

      Create a component that has an <h1> tag with the heading:

      state-context-tutorial/src/components/SaladMaker/SaladMaker.js

      import React from 'react';
      import { createUseStyles } from 'react-jss';
      
      const useStyles = createUseStyles({
        wrapper: {
          textAlign: 'center',
        }
      });
      
      export default function SaladMaker() {
        const classes = useStyles();
        return(
          <>
            <h1 className={classes.wrapper}>
              <span role="img" aria-label="salad">🥗 </span>
                Build Your Custom Salad!
                <span role="img" aria-label="salad"> 🥗</span>
            </h1>
          </>
        )
      }
      

      In this code, you are using textAlign to center the component on the page. The role and aria-label attributes of the span element will help with accessibility using Accessible Rich Internet Applications (ARIA).

      Save and close the file. Open App.js to render the component:

      • nano src/components/App/App.js

      Import SaladMaker and render after the Navigation component:

      state-context-tutorial/src/components/App/App.js

      import React from 'react';
      import Navigation from '../Navigation/Navigation';
      import SaladMaker from '../SaladMaker/SaladMaker';
      
      function App() {
        return (
          <>
            <Navigation />
            <SaladMaker />
          </>
        );
      }
      
      export default App;
      

      Save and close the file. When you do, the page will reload and you’ll see the heading:

      Salad Maker Page

      Next, create a component called SaladItem. This will be a card for each individual ingredient.

      Open the file in your text editor:

      • nano src/components/SaladItem/SaladItem.js

      This component will have three parts: the name of the item, an icon showing if the item is a favorite of the user, and an emoji placed inside a button that will add the item to the salad on click. Add the following lines to SaladItem.js:

      state-context-tutorial/src/components/SaladItem/SaladItem.js

      import React from 'react';
      import PropTypes from 'prop-types';
      import { createUseStyles } from 'react-jss';
      
      const useStyles = createUseStyles({
        add: {
          background: 'none',
          border: 'none',
          cursor: 'pointer',
        },
        favorite: {
          fontSize: 20,
          position: 'absolute',
          top: 10,
          right: 10,
        },
        image: {
          fontSize: 80
        },
        wrapper: {
          border: 'lightgrey solid 1px',
          margin: 20,
          padding: 25,
          position: 'relative',
          textAlign: 'center',
          textTransform: 'capitalize',
          width: 200,
        }
      });
      
      export default function SaladItem({ image, name }) {
        const classes = useStyles();
        const favorite = true;
        return(
          <div className={classes.wrapper}>
              <h3>
                {name}
              </h3>
              <span className={classes.favorite} aria-label={favorite ? 'Favorite' : 'Not Favorite'}>
                {favorite ? '😋' : ''}
              </span>
              <button className={classes.add}>
                <span className={classes.image} role="img" aria-label={name}>{image}</span>
              </button>
          </div>
        )
      }
      
      SaladItem.propTypes = {
        image: PropTypes.string.isRequired,
        name: PropTypes.string.isRequired,
      }
      

      The image and name will be props. The code uses the favorite variable and ternary operators to conditionally determine if the favorite icon appears or not. The favorite variable will later be determined with context as part of the user’s profile. For now, set it to true. The styling will place the favorite icon in the upper right corner of the card and remove the default border and background on the button. The wrapper class will add a small border and transform some of the text. Finally, PropTypes adds a weak typing system to provide some enforcement to make sure the wrong prop type is not passed.

      Save and close the file. Now, you’ll need to render the different items. You’ll do that with a component called SaladBuilder, which will contain a list of items that it will convert to a series of SaladItem components:

      Open SaladBuilder:

      • nano src/components/SaladBuilder/SaladBuilder.js

      If this were a production app, this data would often come from an Application Programming Interface (API). But for now, use a hard-coded list of ingredients:

      state-context-tutorial/src/components/SaladBuilder/SaladBuilder.js

      import React from 'react';
      import SaladItem from '../SaladItem/SaladItem';
      
      import { createUseStyles } from 'react-jss';
      
      const useStyles = createUseStyles({
        wrapper: {
          display: 'flex',
          flexWrap: 'wrap',
          padding: [10, 50],
          justifyContent: 'center',
        }
      });
      
      const ingredients = [
        {
          image: '🍎',
          name: 'apple',
        },
        {
          image: '🥑',
          name: 'avocado',
        },
        {
          image: '🥦',
          name: 'broccoli',
        },
        {
          image: '🥕',
          name: 'carrot',
        },
        {
          image: '🍷',
          name: 'red wine dressing',
        },
        {
          image: '🍚',
          name: 'seasoned rice',
        },
      ];
      
      export default function SaladBuilder() {
        const classes = useStyles();
        return(
          <div className={classes.wrapper}>
            {
              ingredients.map(ingredient => (
                <SaladItem
                  key={ingredient.name}
                  image={ingredient.image}
                  name={ingredient.name}
                />
              ))
            }
          </div>
        )
      }
      

      This snippet uses the map() array method to map over each item in the list, passing the name and image as props to a SaladItem component. Be sure to add a key to each item as you map. The styling for this component adds a display of flex for the flexbox layout, wraps the components, and centers them.

      Save and close the file.

      Finally, render the component in SaladMaker so it will appear in the page.

      Open SaladMaker:

      • nano src/components/SaladMaker/SaladMaker.js

      Then import SaladBuilder and render after the heading:

      state-context-tutorial/src/components/SaladMaker/SaladMaker.js

      import React from 'react';
      import { createUseStyles } from 'react-jss';
      import SaladBuilder from '../SaladBuilder/SaladBuilder';
      
      const useStyles = createUseStyles({
        wrapper: {
          textAlign: 'center',
        }
      });
      
      export default function SaladMaker() {
        const classes = useStyles();
        return(
          <>
            <h1 className={classes.wrapper}>
              <span role="img" aria-label="salad">🥗 </span>
                Build Your Custom Salad!
                <span role="img" aria-label="salad"> 🥗</span>
            </h1>
            <SaladBuilder />
          </>
        )
      }
      

      Save and close the file. When you do the page will reload and you’ll find the content:

      Salad Builder with Items

      The last step is to add the summary of the salad in progress. This component will show a list of items a user has selected. For now, you’ll hard-code the items. You’ll update them with context in Step 3.

      Open SaladSummary in your text editor:

      • nano src/components/SaladSummary/SaladSummary.js

      The component will be a heading and an unsorted list of items. You’ll use flexbox to make them wrap:

      state-context-tutorial/src/components/SaladSummary/SaladSummary.jss

      import React from 'react';
      import { createUseStyles } from 'react-jss';
      
      const useStyles = createUseStyles({
        list: {
          display: 'flex',
          flexDirection: 'column',
          flexWrap: 'wrap',
          maxHeight: 50,
          '& li': {
            width: 100
          }
        },
        wrapper: {
          borderTop: 'black solid 1px',
          display: 'flex',
          padding: 25,
        }
      });
      
      export default function SaladSummary() {
        const classes = useStyles();
        return(
          <div className={classes.wrapper}>
            <h2>Your Salad</h2>
            <ul className={classes.list}>
              <li>Apple</li>
              <li>Avocado</li>
              <li>Carrots</li>
            </ul>
          </div>
        )
      }
      

      Save the file. Then open SaladMaker to render the item:

      • nano src/components/SaladMaker/SaladMaker.js

      Import and add SaladSummary after the SaladBuilder:

      state-context-tutorial/src/components/SaladMaker/SaladMaker.js

      import React from 'react';
      import { createUseStyles } from 'react-jss';
      import SaladBuilder from '../SaladBuilder/SaladBuilder';
      import SaladSummary from '../SaladSummary/SaladSummary';
      
      const useStyles = createUseStyles({
        wrapper: {
          textAlign: 'center',
        }
      });
      
      export default function SaladMaker() {
        const classes = useStyles();
        return(
          <>
            <h1 className={classes.wrapper}>
              <span role="img" aria-label="salad">🥗 </span>
                Build Your Custom Salad!
                <span role="img" aria-label="salad"> 🥗</span>
            </h1>
            <SaladBuilder />
            <SaladSummary />
          </>
        )
      }
      

      Save and close the file. When you do, the page will refresh and you’ll find the full application:

      Salad Builder Site

      There is shared data throughout the application. The Navigation component and the SaladItem component both need to know something about the user: their name and their list of favorites. The SaladItem also needs to update data that is accessible in the SaladSummary component. The components share common ancestors, but passing the data down through the tree would be difficult and error prone.

      That’s where context comes in. You can declare the data in a common parent and then access later without explicitly passing it down the hierarchy of components.

      In this step, you created an application to allow the user to build a salad from a list of options. You created a set of components that need to access or update data that is controlled by other components. In the next step, you’ll use context to store data and access it in child components.

      Step 2 — Providing Data from a Root Component

      In this step, you’ll use context to store the customer information at the root of the component. You’ll create a custom context, then use a special wrapping component called a Provider that will store the information at the root of the project. You’ll then use the useContext Hook to connect with the provider in nested components so you can display the static information. By the end of this step, you’ll be able to provide centralized stores of information and use information stored in a context in many different components.

      Context at its most basic is an interface for sharing information. Many applications have some universal information they need to share across the application, such as user preferences, theming information, and site-wide application changes. With context, you can store that information at the root level then access it anywhere. Since you set the information in a parent, you know it will always be available and it will always be up-to-date.

      To add a context, create a new directory called User:

      • mkdir src/components/User

      User isn’t going to be a traditional component, in that you are going to use it both as a component and as a piece of data for a special Hook called useContext. For now, keep the flat file structure, but if you use a lot of contexts, it might be worth moving them to a different directory structure.

      Next, open up User.js in your text editor:

      • nano src/components/User/User.js

      Inside the file, import the createContext function from React, then execute the function and export the result:

      state-context-tutorial/src/components/User/User.js

      import { createContext } from 'react';
      
      const UserContext = createContext();
      export default UserContext;
      

      By executing the function, you have registered the context. The result, UserContext, is what you will use in your components.

      Save and close the file.

      The next step is to apply the context to a set of elements. To do that, you will use a component called a Provider. The Provider is a component that sets the data and then wraps some child components. Any wrapped child components will have access to data from the Provider with the useContext Hook.

      Since the user data will be constant across the project, put it as high up the component tree as you can. In this application, you will put it at the root level in the App component:

      Open up App:

      • nano src/components/App/App.js

      Add in the following highlighted lines of code to import the context and pass along the data:

      state-context-tutorial/src/components/App/App.js

      import React from 'react';
      import Navigation from '../Navigation/Navigation';
      import SaladMaker from '../SaladMaker/SaladMaker';
      import UserContext from '../User/User';
      
      const user = {
        name: 'Kwame',
        favorites: [
          'avocado',
          'carrot'
        ]
      }
      
      function App() {
        return (
          <UserContext.Provider value={user}>
            <Navigation />
            <SaladMaker />
          </UserContext.Provider>
        );
      }
      
      export default App;
      

      In a typical application, you would fetch the user data or have it stored during a server-side render. In this case, you hard-coded some data that you might receive from an API. You created an object called user that holds the username as a string and an array of favorite ingredients.

      Next, you imported the UserContext, then wrapped Navigation and SaladMaker with a component called the UserContext.Provider. Notice how in this case UserContext is acting as a standard React component. This component will take a single prop called value. That prop will be the data you want to share, which in this case is the user object.

      Save and close the file. Now the data is available throughout the application. However, to use the data, you’ll need to once again import and access the context.

      Now that you have set context, you can start replacing hard-coded data in your component with dynamic values. Start by replacing the hard-coded name in Navigation with the user data you set with UserContext.Provider.

      Open Navigation.js:

      • nano src/components/Navigation/Navigation.js

      Inside of Navigation, import the useContext Hook from React and UserContext from the component directory. Then call useContext using UserContext as an argument. Unlike the UserContext.Provider, you do not need to render UserContext in the JSX. The Hook will return the data that you provided in the value prop. Save the data to a new variable called user, which is an object containing name and favorites. You can then replace the hard-coded name with user.name:

      state-context-tutorial/src/components/Navigation/Navigation.js

      import React, { useContext } from 'react';
      import { createUseStyles } from 'react-jss';
      
      import UserContext from '../User/User';
      
      const useStyles = createUseStyles({
        wrapper: {
          outline: 'black solid 1px',
          padding: [15, 10],
          textAlign: 'right',
        }
      });
      
      export default function Navigation() {
        const user = useContext(UserContext);
        const classes = useStyles();
        return(
          <div className={classes.wrapper}>
            Welcome, {user.name}
          </div>
        )
      }
      

      UserContext worked as a component in App.js, but here you are using it more as a piece of data. However, it can still act as a component if you would like. You can access the same data by using a Consumer that is part of the UserContext. You retrieve the data by adding UserContext.Consumer to your JSX, then use a function as a child to access the data.

      While it’s possible to use the Consumer component, using Hooks can often be shorter and easier to read, while still providing the same up-to-date information. This is why this tutorial uses the Hooks approach.

      Save and close the file. When you do, the page will refresh and you’ll see the same name. But this time it has updated dynamically:

      Salad Builder Site

      In this case the data didn’t travel across many components. The component tree that represents the path that the data traveled would look like this:

      | UserContext.Provider
        | Navigation
      

      You could pass this username as a prop, and at this scale that could be an effective strategy. But as the application grows, there’s a chance that the Navigation component will move. There may be a component called Header that wraps the Navigation component and another component such as a TitleBar, or maybe you’ll create a Template component and then nest the Navigation in there. By using context, you won’t have to refactor Navigation as long as the Provider is up the tree, making refactoring easier.

      The next component that needs user data is the SaladItem component. In the SaladItem component, you’ll need the user’s array of favorites. You’ll conditionally display the emoji if the ingredient is a favorite of the user.

      Open SaladItem.js:

      • nano src/components/SaladItem/SaladItem.js

      Import useContext and UserContext, then call useContext with UserContext. After that, check to see if the ingredient is in the favorites array using the includes method:

      state-context-tutorial/src/components/SaladItem/SaladItem.js

      import React, { useContext } from 'react';
      import PropTypes from 'prop-types';
      import { createUseStyles } from 'react-jss';
      
      import UserContext from '../User/User';
      
      const useStyles = createUseStyles({
      ...
      });
      
      export default function SaladItem({ image, name }) {
        const classes = useStyles();
        const user = useContext(UserContext);
        const favorite = user.favorites.includes(name);
        return(
          <div className={classes.wrapper}>
              <h3>
                {name}
              </h3>
              <span className={classes.favorite} aria-label={favorite ? 'Favorite' : 'Not Favorite'}>
                {favorite ? '😋' : ''}
              </span>
              <button className={classes.add}>
                <span className={classes.image} role="img" aria-label={name}>{image}</span>
              </button>
          </div>
        )
      }
      
      SaladItem.propTypes = {
        image: PropTypes.string.isRequired,
        name: PropTypes.string.isRequired,
      }
      

      Save and close the file. When you do, the browser will refresh and you’ll see that only the favorite items have the emoji:

      Salad Maker with Avocado and Carrot favorited

      Unlike Navigation, the context is traveling much farther. The component tree would look something like this:

      | User.Provider
        | SaladMaker
          | SaladBuilder
            | SaladItem
      

      The information skipped over two intermediary components without any props. If you had to pass the data as a prop all the way through the tree, it would be a lot of work and you’d risk having a future developer refactor the code and forget to pass the prop down. With context, you can be confident the code will work as the application grows and evolves.

      In this step, you created a context and used a Provider to set the data in the component tree. You also accessed context with the useContext Hook and used context across multiple components. This data was static and thus never changed after the initial set up, but there are going to be times when you need to share data and also modify the data across multiple components. In the next step, you’ll update nested data using context.

      Step 3 — Updating Data from Nested Components

      In this step, you’ll use context and the useReducer Hook to create dynamic data that nested components can consume and update. You’ll update your SaladItem components to set data that the SaladSummary will use and display. You’ll also set context providers outside of the root component. By the end of this step, you’ll have an application that can use and update data across several components and you’ll be able to add multiple context providers at different levels of an application.

      At this point, your application is displaying user data across multiple components, but it lacks any user interaction. In the previous step, you used context to share a single piece of data, but you can also share a collection of data, including functions. That means you can share data and also share the function to update the data.

      In your application, each SaladItem needs to update a shared list. Then your SaladSummary component will display the items the user has selected and add it to the list. The problem is that these components are not direct descendants, so you can’t pass the data and the update functions as props. But they do share a common parent: SaladMaker.

      One of the big differences between context and other state management solutions such as Redux is that context is not intended to be a central store. You can use it multiple times throughout an application and initiate it at the root level or deep in a component tree. In other words, you can spread your contexts throughout the application, creating focused data collections without worrying about conflicts.

      To keep context focused, create Providers that wrap the nearest shared parent when possible. In this case, that means, rather than adding another context in App, you will add the context in the SaladMaker component.

      Open SaladMaker:

      • nano src/components/SaladMaker/SaladMaker.js

      Then create and export a new context called SaladContext:

      state-context-tutorial/src/components/SaladMaker/SaladMaker.js

      import React, { createContext } from 'react';
      import { createUseStyles } from 'react-jss';
      import SaladBuilder from '../SaladBuilder/SaladBuilder';
      import SaladSummary from '../SaladSummary/SaladSummary';
      
      const useStyles = createUseStyles({
        wrapper: {
          textAlign: 'center',
        }
      });
      
      export const SaladContext = createContext();
      
      export default function SaladMaker() {
        const classes = useStyles();
        return(
          <>
            <h1 className={classes.wrapper}>
              <span role="img" aria-label="salad">🥗 </span>
                Build Your Custom Salad!
                <span role="img" aria-label="salad"> 🥗</span>
            </h1>
            <SaladBuilder />
            <SaladSummary />
          </>
        )
      }
      

      In the previous step, you made a separate component for your context, but in this case you are creating it in the same file that you are using it. Since User does not seem related directly to the App, it might make more sense to keep them separate. However, since the SaladContext is tied closely to the SaladMaker component, keeping them together will create more readable code.

      In addition, you could create a more generic context called OrderContext, which you could reuse across multiple components. In that case, you’d want to make a separate component. For now, keep them together. You can always refactor later if you decide to shift to another pattern.

      Before you add the Provider think about the data that you want to share. You’ll need an array of items and a function for adding the items. Unlike other centralized state management tools, context does not handle updates to your data. It merely holds the data for use later. To update data, you’ll need to use other state management tools such as Hooks. If you were collecting data for the same component, you’d use either the useState or useReducer Hooks. If you are new to these Hooks, check out How To Manage State with Hooks on React Components.

      The useReducer Hook is a good fit since you’ll need to update the most recent state on every action.

      Create a reducer function that adds a new item to a state array, then use the useReducer Hook to create a salad array and a setSalad function:

      state-context-tutorial/src/components/SaladMaker/SaladMaker.js

      import React, { useReducer, createContext } from 'react';
      import { createUseStyles } from 'react-jss';
      import SaladBuilder from '../SaladBuilder/SaladBuilder';
      import SaladSummary from '../SaladSummary/SaladSummary';
      
      const useStyles = createUseStyles({
        wrapper: {
          textAlign: 'center',
        }
      });
      
      export const SaladContext = createContext();
      
      function reducer(state, item) {
        return [...state, item]
      }
      
      export default function SaladMaker() {
        const classes = useStyles();
        const [salad, setSalad] = useReducer(reducer, []);
        return(
          <>
            <h1 className={classes.wrapper}>
              <span role="img" aria-label="salad">🥗 </span>
                Build Your Custom Salad!
                <span role="img" aria-label="salad"> 🥗</span>
            </h1>
            <SaladBuilder />
            <SaladSummary />
          </>
        )
      }
      

      Now you have a component that contains the salad data you want to share, a function called setSalad to update the data, and the SaladContext to share the data in the same component. At this point, you need to combine them together.

      To combine, you’ll need to create a Provider. The problem is that the Provider takes a single value as a prop. Since you can’t pass salad and setSalad individually, you’ll need to combine them into an object and pass the object as the value:

      state-context-tutorial/src/components/SaladMaker/SaladMaker.js

      import React, { useReducer, createContext } from 'react';
      import { createUseStyles } from 'react-jss';
      import SaladBuilder from '../SaladBuilder/SaladBuilder';
      import SaladSummary from '../SaladSummary/SaladSummary';
      
      const useStyles = createUseStyles({
        wrapper: {
          textAlign: 'center',
        }
      });
      
      export const SaladContext = createContext();
      
      function reducer(state, item) {
        return [...state, item]
      }
      
      export default function SaladMaker() {
        const classes = useStyles();
        const [salad, setSalad] = useReducer(reducer, []);
        return(
          <SaladContext.Provider value={{ salad, setSalad }}>
            <h1 className={classes.wrapper}>
              <span role="img" aria-label="salad">🥗 </span>
                Build Your Custom Salad!
                <span role="img" aria-label="salad"> 🥗</span>
            </h1>
            <SaladBuilder />
            <SaladSummary />
          </SaladContext.Provider>
        )
      }
      

      Save and close the file. As with Navigation, it may seem unnecessary to create a context when the SaladSummary is in the same component as the context. Passing salad as a prop is perfectly reasonable, but you may end up refactoring it later. Using context here keeps the information together in a single place.

      Next, go into the SaladItem component and pull the setSalad function out of the context.

      Open the component in a text editor:

      • nano src/components/SaladItem/SaladItem.js

      Inside SaladItem, import the context from SaladMaker, then pull out the setSalad function using destructuring. Add a click event to the button that will call the setSalad function. Since you want a user to be able to add an item multiple times, you’ll also need to create a unique id for each item so that the map function will be able to assign a unique key:

      state-context-tutorial/src/components/SaladItem/SaladItem.js

      import React, { useReducer, useContext } from 'react';
      import PropTypes from 'prop-types';
      import { createUseStyles } from 'react-jss';
      
      import UserContext from '../User/User';
      import { SaladContext } from '../SaladMaker/SaladMaker';
      
      const useStyles = createUseStyles({
      ...
      });
      
      const reducer = key => key + 1;
      export default function SaladItem({ image, name }) {
        const classes = useStyles();
        const { setSalad } = useContext(SaladContext)
        const user = useContext(UserContext);
        const favorite = user.favorites.includes(name);
        const [id, updateId] = useReducer(reducer, 0);
        function update() {
          setSalad({
            name,
            id: `${name}-${id}`
          })
          updateId();
        };
        return(
          <div className={classes.wrapper}>
              <h3>
                {name}
              </h3>
              <span className={classes.favorite} aria-label={favorite ? 'Favorite' : 'Not Favorite'}>
                {favorite ? '😋' : ''}
              </span>
              <button className={classes.add} onClick={update}>
                <span className={classes.image} role="img" aria-label={name}>{image}</span>
              </button>
          </div>
        )
      }
      ...
      

      To make the unique id, you’ll use the useReducer Hook to increment a value on every click. For the first click, the id will be 0; the second will be 1, and so on. You’ll never display this value to the user; this will just create a unique value for the mapping function later.

      After creating the unique id, you created a function called update to increment the id and to call setSalad. Finally, you attached the function to the button with the onClick prop.

      Save and close the file. The last step is to pull the dynamic data from the context in the SaladSummary.

      Open SaladSummary:

      • nano src/components/SaladSummary/SaladSummary.js

      Import the SaladContext component, then pull out the salad data using destructuring. Replace the hard-coded list items with a function that maps over salad, converting the objects to <li> elements. Be sure to use the id as the key:

      state-context-tutorial/src/components/SaladSummary/SaladSummary.js

      import React, { useContext } from 'react';
      import { createUseStyles } from 'react-jss';
      
      import { SaladContext } from '../SaladMaker/SaladMaker';
      
      const useStyles = createUseStyles({
      ...
      });
      
      export default function SaladSummary() {
        const classes = useStyles();
        const { salad } = useContext(SaladContext);
        return(
          <div className={classes.wrapper}>
            <h2>Your Salad</h2>
            <ul className={classes.list}>
              {salad.map(({ name, id }) => (<li key={id}>{name}</li>))}
            </ul>
          </div>
        )
      }
      

      Save and close the file. When you do, you will be able to click on items and it will update the summary:

      Adding salad items

      Notice how the context gave you the ability to share and update data in different components. The context didn’t update the items itself, but it gave you a way to use the useReducer Hook across multiple components. In addition, you also had the freedom to put the context lower in the tree. It may seem like it’s best to always keep the context at the root, but by keeping the context lower, you don’t have to worry about unused state sticking around in a central store. As soon as you unmount a component, the data disappears. That can be a problem if you ever want to save the data, but in that case, you just need to raise the context up to a higher parent.

      Another advantage of using context lower in your application tree is that you can reuse a context without worrying about conflicts. Suppose you had a larger app that had a sandwich maker and a salad maker. You could create a generic context called OrderContext and then you could use it at multiple points in your component without worrying about data or name conflicts. If you had a SaladMaker and a SandwichMaker, the tree would look something like this:

      | App
        | Salads
          | OrderContext
            | SaladMaker
        | Sandwiches
          | OrderContext
            | SandwichMaker
      

      Notice that OrderContext is there twice. That’s fine, since the useContext Hook will look for the nearest provider.

      In this step you shared and updated data using context. You also placed the context outside the root element so it’s close to the components that need the information without cluttering a root component. Finally, you combined context with state management Hooks to create data that is dynamic and accessible across several components.

      Conclusion

      Context is a powerful and flexible tool that gives you the ability to store and use data across an application. It gives you the ability to handle distributed data with built-in tools that do not require any additional third party installation or configuration.

      Creating reusable contexts is important across a variety of common components such as forms that need to access data across elements or tab views that need a common context for both the tab and the display. You can store many types of information in contexts including themes, form data, alert messages, and more. Context gives you the freedom to build components that can access data without worrying about how to pass data through intermediary components or how to store data in a centralized store without making the store too large.

      If you would like to look at more React tutorials, check out our React Topic page, or return to the How To Code in React.js series page.



      Source link

      How To Manage State with Hooks on React Components


      The author selected Creative Commons to receive a donation as part of the Write for DOnations program.

      Introduction

      In React development, keeping track of how your application data changes over time is called state management. By managing the state of your application, you will be able to make dynamic apps that respond to user input. There are many methods of managing state in React, including class-based state management and third-party libraries like Redux. In this tutorial, you’ll manage state on functional components using a method encouraged by the official React documentation: Hooks.

      Hooks are a broad set of tools that run custom functions when a component’s props change. Since this method of state management doesn’t require you to use classes, developers can use Hooks to write shorter, more readable code that is easy to share and maintain. One of the main differences between Hooks and class-based state management is that there is no single object that holds all of the state. Instead, you can break up state into multiple pieces that you can update independently.

      Throughout this tutorial, you’ll learn how to set state using the useState and useReducer Hooks. The useState Hook is valuable when setting a value without referencing the current state; the useReducer Hook is useful when you need to reference a previous value or when you have different actions the require complex data manipulations. To explore these different ways of setting state, you’ll create a product page component with a shopping cart that you’ll update by adding purchases from a list of options. By the end of this tutorial, you’ll be comfortable managing state in a functional component using Hooks, and you’ll have a foundation for more advanced Hooks such as useEffect, useMemo, and useContext.

      Prerequisites

      Step 1 – Setting Initial State in a Component

      In this step, you’ll set the initial state on a component by assigning the initial state to a custom variable using the useState Hook. To explore Hooks, you’ll make a product page with a shopping cart, then display the initial values based on the state. By the end of the step, you’ll know the different ways to hold a state value using Hooks and when to use state rather than a prop or a static value.

      Start by creating a directory for a Product component:

      • mkdir src/components/Product

      Next, open up a file called Product.js in the Product directory:

      • nano src/components/Product/Product.js

      Start by creating a component with no state. The component will consist of two parts: the cart, which has the number of items and the total price, and the product, which has a button to add or remove the item from the cart. For now, these buttons will have no function.

      Add the following code to the file:

      hooks-tutorial/src/components/Product/Product.js

      import React from 'react';
      import './Product.css';
      
      export default function Product() {
        return(
          <div className="wrapper">
            <div>
              Shopping Cart: 0 total items.
            </div>
            <div>Total: 0</div>
      
            <div className="product"><span role="img" aria-label="ice cream">🍦</span></div>
            <button>Add</button> <button>Remove</button>
          </div>
        )
      }
      

      In this code, you used JSX to create the HTML elements for the Product component, with an ice cream emoji to represent the product. In addition, two of the <div> elements have class names so you can add some basic CSS styling.

      Save and close the file, then create a new file called Product.css in the Product directory:

      • nano src/components/Product/Product.css

      Add some styling to increase the font size for the text and the emoji:

      hooks-tutorial/src/components/Product/Product.css

      .product span {
          font-size: 100px;
      }
      
      .wrapper {
          padding: 20px;
          font-size: 20px;
      }
      
      .wrapper button {
          font-size: 20px;
          background: none;
          border: black solid 1px;
      }
      

      The emoji will need a much larger font-size, since it’s acting as the product image. In addition, you are removing the default gradient background on the button by setting background to none.

      Save and close the file. Now, add the component into the App component to render the Product component in the browser. Open App.js:

      • nano src/components/App/App.js

      Import the component and render it. Also, delete the CSS import since you won’t be using it in this tutorial:

      hooks-tutorial/src/components/App/App.js

      import React from 'react';
      import Product from '../Product/Product';
      
      function App() {
        return <Product />
      }
      
      export default App;
      

      Save and close the file. When you do, the browser will refresh and you’ll see the Product component:

      Product Page

      Now that you have a working component, you can replace the hard-coded data with dynamic values.

      React exports several Hooks that you can import directly from the main React package. By convention, React Hooks start with the word use, such as useState, useContext, and useReducer. Most third-party libraries follow the same convention. For example, Redux has a useSelector and a useStore Hook.

      Hooks are functions that let you run actions as part of the React lifecycle. Hooks are triggered either by other actions or by changes in a component’s props and are used to either create data or to trigger further changes. For example, the useState Hook generates a stateful piece of data along with a function for changing that piece of data and triggering a re-render. It will create a dynamic piece of code and hook into the lifecycle by triggering re-renders when the data changes. In practice, that means you can store dynamic pieces of data in variables using the useState Hook.

      For example, in this component, you have two pieces of data that will change based on user actions: the cart and the total cost. Each of these can be stored in state using the above Hook.

      To try this out, open up Product.js:

      • nano src/components/Product/Product.js

      Next, import the useState Hook from React by adding the highlighted code:

      hooks-tutorial/src/components/Product/Product.js

      import React, { useState } from 'react';
      import './Product.css';
      
      export default function Product() {
        return(
          <div className="wrapper">
            <div>
              Shopping Cart: 0 total items.
            </div>
            <div>Total: 0</div>
      
            <div className="product"><span role="img" aria-label="ice cream">🍦</span></div>
            <button>Add</button> <button>Remove</button>
          </div>
        )
      }
      

      useState is a function that takes the initial state as an argument and returns an array with two items. The first item is a variable containing the state, which you will often use in your JSX. The second item in the array is a function that will update the state. Since React returns the data as an array, you can use destructuring to assign the values to any variable names you want. That means you can call useState many times and never have to worry about name conflicts, since you can assign every piece of state and update function to a clearly named variable.

      Create your first Hook by invoking the useState Hook with an empty array. Add in the following highlighted code:

      hooks-tutorial/src/components/Product/Product.js

      import React, { useState } from 'react';
      import './Product.css';
      
      export default function Product() {
        const [cart, setCart] = useState([]);
        return(
          <div className="wrapper">
            <div>
              Shopping Cart: {cart.length} total items.
            </div>
            <div>Total: 0</div>
      
            <div className="product"><span role="img" aria-label="ice cream">🍦</span></div>
            <button>Add</button> <button>Remove</button>
          </div>
        )
      }
      

      Here you assigned the first value, the state, to a variable called cart. cart will be an array that contains the products in the cart. By passing an empty array as an argument to useState, you set the initial empty state as the first value of cart.

      In addition to the cart variable, you assigned the update function to a variable called setCart. At this point, you aren’t using the setCart function, and you may see a warning about having an unused variable. Ignore this warning for now; in the next step, you’ll use setCart to update the cart state.

      Save the file. When the browser reloads, you’ll see the page without changes:

      Product Page

      One important difference between Hooks and class-based state management is that, in class-based state management, there is a single state object. With Hooks, state objects are completely independent of each other, so you can have as many state objects as you want. That means that if you want a new piece of stateful data, all you need to do is call useState with a new default and assign the result to new variables.

      Inside Product.js, try this out by creating a new piece of state to hold the total. Set the default value to 0 and assign the value and function to total and setTotal:

      hooks-tutorial/src/components/Product/Product.js

      import React, { useState } from 'react';
      import './Product.css';
      
      export default function Product() {
        const [cart, setCart] = useState([]);
        const [total, setTotal] = useState(0);
        return(
          <div className="wrapper">
            <div>
              Shopping Cart: {cart.length} total items.
            </div>
            <div>Total: {total}</div>
      
            <div className="product"><span role="img" aria-label="ice cream">🍦</span></div>
            <button>Add</button> <button>Remove</button>
          </div>
        )
      }
      

      Now that you have some stateful data, you can standardize the displayed data to make a more predictable experience. For example, since the total in this example is a price, it will always have two decimal places. You can use the toLocaleString method to convert total from a number to a string with two decimal places. It will also convert the number to a string according to the numerical conventions that match the browser’s locale. You’ll set the options minimumFractionDigits and maximumFractionDigits to give a consistent number of decimal places.

      Create a function called getTotal. This function will use the in-scope variable total and return a localized string that you will use to display the total. Use undefined as the first argument to toLocaleString to use the system locale rather than specifying a locale:

      hooks-tutorial/src/components/Product/Product.js

      import React, { useState } from 'react';
      import './Product.css';
      
      const currencyOptions = {
        minimumFractionDigits: 2,
        maximumFractionDigits: 2,
      }
      
      export default function Product() {
        const [cart, setCart] = useState([]);
        const [total, setTotal] = useState(0);
      
        function getTotal() {
          return total.toLocaleString(undefined, currencyOptions)
        }
      
        return(
          <div className="wrapper">
            <div>
              Shopping Cart: {cart.length} total items.
            </div>
            <div>Total: {getTotal()}</div>
      
            <div className="product"><span role="img" aria-label="ice cream">🍦</span></div>
            <button>Add</button> <button>Remove</button>
          </div>
        )
      }
      

      You now have added some string processing to the displayed total. Even though getTotal is a separate function, it shares the same scope as the surrounding function, which means it can reference the variables of the component.

      Save the file. The page will reload and you’ll see the updated total with two decimal places:

      Price converted to decimal

      This function works, but as of now, getTotal can only operate in this piece of code. In this case, you can convert it to a pure function, which gives the same outputs when given the same inputs and does not rely on a specific environment to operate. By converting the function to a pure function, you make it more reusable. You can, for example, extract it to a separate file and use it in multiple components.

      Update getTotal to take total as an argument. Then move the function outside of the component:

      hooks-tutorial/src/components/Product/Product.js

      import React, { useState } from 'react';
      import './Product.css';
      
      const currencyOptions = {
        minimumFractionDigits: 2,
        maximumFractionDigits: 2,
      }
      
      function getTotal(total) {
        return total.toLocaleString(undefined, currencyOptions)
      }
      
      export default function Product() {
        const [cart, setCart] = useState([]);
        const [total, setTotal] = useState(0);
      
      
        return(
          <div className="wrapper">
            <div>
              Shopping Cart: {cart.length} total items.
            </div>
            <div>Total: {getTotal(total)}</div><^>
      
            <div className="product"><span role="img" aria-label="ice cream">🍦</span></div>
            <button>Add</button> <button>Remove</button>
          </div>
        )
      }
      

      Save the file. When you do, the page will reload and you’ll see the component as it was before.

      Functional components like this make it easier to move functions around. As long as there are no scope conflicts, you can move these conversion functions anywhere you want.

      In this step, you set the default value for a stateful piece of data using useState. You then saved the stateful data and a function for updating the state to variables using array destructuring. In the next step, you’ll use the update function to change the state value to re-render the page with updated information.

      Step 2 — Setting State with useState

      In this step, you’ll update your product page by setting a new state with a static value. You have already created the function to update a piece of state, so now you’ll create an event to update both stateful variables with predefined values. By the end of this step, you’ll have a page with state that a user will be able to update at the click of a button.

      Unlike class-based components, you cannot update several pieces of state with a single function call. Instead, you must call each function individually. This means there is a greater separation of concerns, which helps keep stateful objects focused.

      Create a function to add an item to the cart and update the total with the price of the item, then add that functionality to the Add button:

      hooks-tutorial/src/components/Product/Product.js

      import React, { useState } from 'react';
      
      ...
      
      export default function Product() {
        const [cart, setCart] = useState([]);
        const [total, setTotal] = useState(0);
      
        function add() {
          setCart(['ice cream']);
          setTotal(5);
        }
      
        return(
          <div className="wrapper">
            <div>
              Shopping Cart: {cart.length} total items.
            </div>
            <div>Total: {getTotal(total)}</div>
      
            <div className="product"><span role="img" aria-label="ice cream">🍦</span></div>
            <button onClick={add}>Add</button><^>
            <button>Remove</button>
          </div>
        )
      }
      

      In this snippet, you called setCart with an array containing the word “ice cream” and called setTotal with 5. You then added this function to the onClick event handler for the Add button.

      Notice that the function must have the same scope as the functions to set state, so it must be defined inside the component function.

      Save the file. When you do, the browser will reload, and when you click on the Add button the cart will update with the current amount:

      Click on the button and see state updated

      Since you are not referencing a this context, you can use either an arrow function or a function declaration. They both work equally well here, and each developer or team can decide which style to use. You can even skip defining an extra function and pass the function directly into the onClick property.

      To try this out, create a function to remove the values by setting the cart to an empty object and the total to 0. Create the function in the onClick prop of the Remove button:

      hooks-tutorial/src/component/Product/Product.js

      import React, { useState } from 'react';
      ...
      export default function Product() {
        const [cart, setCart] = useState([]);
        const [total, setTotal] = useState(0);
      
        function add() {
          setCart(['ice cream']);
          setTotal(5);
        }
      
        return(
          <div className="wrapper">
            <div>
              Shopping Cart: {cart.length} total items.
            </div>
            <div>Total: {getTotal(total)}</div>
      
            <div className="product"><span role="img" aria-label="ice cream">🍦</span></div>
            <button onClick={add}>Add</button>
            <button
              onClick={() => {
                setCart([]);
                setTotal(0);
              }}
            >
              Remove
            </button>
          </div>
        )
      }
      

      Save the file. When you do, you will be able to add and remove an item:

      Add and Remove

      Both strategies for assigning the function work, but there are some slight performance implications to creating an arrow function directly in a prop. In every re-render, React will create a new function, which would trigger a prop change and cause the component to re-render. When you define a function outside of a prop, you can take advantage of another Hook called useCallback. This will memoize the function, meaning that it will only create a new function if certain values change. If nothing changes, the program will use the cached memory of the function instead of recalculating it. Some components may not need that level of optimization, but as a rule, the higher a component is likely to be in a tree, the greater the need for memoization.

      In this step, you updated state data with functions created by the useState Hook. You created wrapping functions to call both functions to update the state of several pieces of data at the same time. But these functions are limited because they add static, pre-defined values instead of using the previous state to create the new state. In the next step, you’ll update the state using the current state with both the useState Hook and a new Hook called useReducer.

      Step 3 — Setting State Using Current State

      In the previous step, you updated state with a static value. It didn’t matter what was in the previous state—you always passed the same value. But a typical product page will have many items that you can add to a cart, and you’ll want to be able to update the cart while preserving the previous items.

      In this step, you’ll update the state using the current state. You’ll expand your product page to include several products and you’ll create functions that update the cart and the total based on the current values. To update the values, you’ll use both the useState Hook and a new Hook called useReducer.

      Since React may optimize code by calling actions asynchronously, you’ll want to make sure that your function has access to the most up-to-date state. The most basic way to solve this problem is to pass a function to the state-setting function instead of a value. In other words, instead of calling setState(5), you’d call setState(previous => previous +5).

      To start implementing this, add some more items to the product page by making a products array of objects, then remove the event handlers from the Add and Remove buttons to make room for the refactoring:

      hooks-tutorial/src/component/Product/Product.js

      import React, { useState } from 'react';
      import './Product.css';
      
      ...
      
      const products = [
        {
          emoji: '🍦',
          name: 'ice cream',
          price: 5
        },
        {
          emoji: '🍩',
          name: 'donuts',
          price: 2.5,
        },
        {
          emoji: '🍉',
          name: 'watermelon',
          price: 4
        }
      ];
      
      export default function Product() {
        const [cart, setCart] = useState([]);
        const [total, setTotal] = useState(0);
      
        function add() {
          setCart(['ice cream']);
          setTotal(5);
        }
      
        return(
          <div className="wrapper">
            <div>
              Shopping Cart: {cart.length} total items.
            </div>
            <div>Total: {getTotal(total)}</div>
              <div>
              {products.map(product => (
                <div key={product.name}>
                  <div className="product">
                    <span role="img" aria-label={product.name}>{product.emoji}</span>
                  </div>
                  <button>Add</button>
                  <button>Remove</button>
                </div>
              ))}
            <^></div><^
          </div>
        )
      }
      

      You now have some JSX that uses the .map method to iterate over the array and display the products.

      Save the file. When you do, the page will reload and you’ll see multiple products:

      Product list

      Currently, the buttons have no actions. Since you only want to add the specific product on click, you’ll need to pass the product as an argument to the add function. In the add function, instead of passing the new item directly to the setCart and setTotal functions, you’ll pass an anonymous function that takes the current state and returns a new updated value:

      hooks-tutorial/src/component/Product/Product.js

      import React, { useState } from 'react';
      import './Product.css';
      ...
      export default function Product() {
        const [cart, setCart] = useState([]);
        const [total, setTotal] = useState(0);
      
        function add(product) {
          setCart(current => [...current, product.name]);
          setTotal(current => current + product.price);
        }
      
        return(
          <div className="wrapper">
            <div>
              Shopping Cart: {cart.length} total items.
            </div>
            <div>Total: {getTotal(total)}</div>
      
            <div>
              {products.map(product => (
                <div key={product.name}>
                  <div className="product">
                    <span role="img" aria-label={product.name}>{product.emoji}</span>
                  </div>
                  <button onClick={() => add(product)}>Add</button>
                  <button>Remove</button>
                </div>
              ))}
            </div>
          </div>
        )
      }
      

      The anonymous function uses the most recent state—either cart or total—as an argument that you can use to create a new value. Take care, though, not to directly mutate state. Instead, when adding a new value to the cart you can add the new product to the state by spreading the current value and adding the new value onto the end.

      Save the file. When you do, the browser will reload and you’ll be able to add multiple products:

      Adding products

      There’s another Hook called useReducer that is specially designed to update the state based on the current state, in a manner similar to the .reduce array method. The useReducer Hook is similar to useState, but when you initialize the Hook, you pass in a function the Hook will run when you change the state along with the initial data. The function—referred to as the reducer—takes two arguments: the state and another argument. The other argument is what you will supply when you call the update function.

      Refactor the cart state to use the useReducer Hook. Create a funciton called cartReducer that takes the state and the product as arguments. Replace useState with useReducer, then pass the cartReducer function as the first argument and an empty array as the second argument, which will be the initial data:

      hooks-tutorial/src/component/Product/Product.js

      import React, { useReducer, useState } from 'react';
      
      ...
      
      function cartReducer(state, product) {
        return [...state, product]
      }
      
      export default function Product() {
        const [cart, setCart] = useReducer(cartReducer, []);
        const [total, setTotal] = useState(0);
      
        function add(product) {
          setCart(product.name);
          setTotal(current => current + product.price);
        }
      
        return(
      ...
        )
      }
      

      Now when you call setCart, pass in the product name instead of a function. When you call setCart, you will call the reducer function, and the product will be the second argument. You can make a similar change with the total state.

      Create a function called totalReducer that takes the current state and adds the new amount. Then replace useState with useReducer and pass the new value setCart instead of a function:

      hooks-tutorial/src/component/Product/Product.js

      import React, { useReducer } from 'react';
      
      ...
      
      function totalReducer(state, price) {
        return state + price;
      }
      
      export default function Product() {
        const [cart, setCart] = useReducer(cartReducer, []);
        const [total, setTotal] = useReducer(totalReducer, 0);
      
        function add(product) {
          setCart(product.name);
          setTotal(product.price);
        }
      
        return(
          ...
        )
      }
      

      Since you are no longer using the useState Hook, you removed it from the import.

      Save the file. When you do, the page will reload and you’ll be able to add items to the cart:

      Adding products

      Now it’s time to add the remove function. But this leads to a problem: The reducer functions can handle adding items and updating totals, but it’s not clear how it will be able to handle removing items from the state. A common pattern in reducer functions is to pass an object as the second argument that contains the name of the action and the data for the action. Inside the reducer, you can then update the total based on the action. In this case, you will add items to the cart on an add action and remove them on a remove action.

      Start with the totalReducer. Update the function to take an action as the second argument, then add a conditional to update the state based on the action.type:

      hooks-tutorial/src/component/Product/Product.js

      import React, { useReducer } from 'react';
      import './Product.css';
      
      ...
      
      function totalReducer(state, action) {
        if(action.type === 'add') {
          return state + action.price;
        }
        return state - action.price
      }
      
      export default function Product() {
        const [cart, setCart] = useReducer(cartReducer, []);
        const [total, setTotal] = useReducer(totalReducer, 0);
      
        function add(product) {
          const { name, price } = product;
          setCart(name);
          setTotal({ price, type: 'add' });
        }
      
        return(
          ...
        )
      }
      

      The action is an object with two properites: type and price. The type can be either add or remove, and the price is a number. If the type is add, it increases the total. If it is remove, it lowers the total. After updating the totalReducer, you call setTotal with a type of add and the price, which you set using destructuring assignment.

      Next, you will update the cartReducer. This one is a little more complicated: You can use if/then conditionals, but it’s more common to use a switch statement. Switch statements are particularly useful if you have a reducer that can handle many different actions because it makes those actions more readable in your code.

      As with the totalReducer, you’ll pass an object as the second item type and name properties. If the action is remove, update the state by splicing out the first instance of a product.

      After updating the cartReducer, create a remove function that calls setCart and setTotal with objects containing type: 'remove' and either the price or the name. Then use a switch statement to update the data based on the action type. Be sure to return the final state:

      hooks-tutorial/src/complicated/Product/Product.js

      import React, { useReducer } from 'react';
      import './Product.css';
      
      ...
      
      function cartReducer(state, action) {
        switch(action.type) {
          case 'add':
            return [...state, action.name];
          case 'remove':
            const update = [...state];
            update.splice(update.indexOf(action.name), 1);
            return update;
          default:
            return state;
        }
      }
      
      function totalReducer(state, action) {
        if(action.type === 'add') {
          return state + action.price;
        }
        return state - action.price
      }
      
      export default function Product() {
        const [cart, setCart] = useReducer(cartReducer, []);
        const [total, setTotal] = useReducer(totalReducer, 0);
      
        function add(product) {
          const { name, price } = product;
          setCart({ name, type: 'add' });
          setTotal({ price, type: 'add' });
        }
      
        function remove(product) {
          const { name, price } = product;
          setCart({ name, type: 'remove' });
          setTotal({ price, type: 'remove' });
        }
      
        return(
          <div className="wrapper">
            <div>
              Shopping Cart: {cart.length} total items.
            </div>
            <div>Total: {getTotal(total)}</div>
      
            <div>
              {products.map(product => (
                <div key={product.name}>
                  <div className="product">
                    <span role="img" aria-label={product.name}>{product.emoji}</span>
                  </div>
                  <button onClick={() => add(product)}>Add</button>
                  <button onClick={() => remove(product)}>Remove</button>
                </div>
              ))}
            </div>
          </div>
        )
      }
      

      As you work on your code, take care not to directly mutate the state in the reducer functions. Instead, make a copy before splicing out the object. Also note it is a best practice to add a default action on a switch statement in order to account for unforeseen edge cases. In this, case just return the object. Other options for the default are throwing an error or falling back to an action such as add or remove.

      After making the changes, save the file. When the browser refreshes, you’ll be able to add and remove items:

      Remove items

      There is still a subtle bug left in this product. In the remove method, you can subtract from a price even if the item is not in the cart. If you click Remove on the ice cream without adding it to your cart, your displayed total will be -5.00.

      You can fix this bug by checking that an item exists before you subtract it, but a more efficient way is to minimize the different pieces of state by only saving related data in one place. In other words, try to avoid double references to the same data, in this case, the product. Instead, store the raw data in one state variable—the whole product object—then perform the calculations using that data.

      Refactor the component so that the add() function passes the whole product to the reducer and the remove() function removes the whole object. The getTotal method will use the cart, and so you can delete the totalReducer function. Then you can pass the cart to getTotal(), which you can refactor to reduce the array to a single value:

      hooks-tutorial/src/component/Product/Product.js

      import React, { useReducer } from 'react';
      import './Product.css';
      
      const currencyOptions = {
        minimumFractionDigits: 2,
        maximumFractionDigits: 2,
      }
      
      function getTotal(cart) {
        const total = cart.reduce((totalCost, item) => totalCost + item.price, 0);
        return total.toLocaleString(undefined, currencyOptions)
      }
      
      ...
      
      function cartReducer(state, action) {
        switch(action.type) {
          case 'add':
            return [...state, action.product];
          case 'remove':
            const productIndex = state.findIndex(item => item.name === action.product.name);
            if(productIndex < 0) {
              return state;
            }
            const update = [...state];
            update.splice(productIndex, 1)
            return update
          default:
            return state;
        }
      }
      
      export default function Product() {
        const [cart, setCart] = useReducer(cartReducer, []);
      
        function add(product) {
          setCart({ product, type: 'add' });
        }
      
        function remove(product) {
          setCart({ product, type: 'remove' });
        } 
      
        return(
          <div className="wrapper">
            <div>
              Shopping Cart: {cart.length} total items.
            </div>
            <div>Total: {getTotal(cart)}</div>
      
            <div>
              {products.map(product => (
                <div key={product.name}>
                  <div className="product">
                    <span role="img" aria-label={product.name}>{product.emoji}</span>
                  </div>
                  <button onClick={() => add(product)}>Add</button>
                  <button onClick={() => remove(product)}>Remove</button>
                </div>
              ))}
            </div>
          </div>
        )
      }
      

      Save the file. When you do, the browser will refresh and you’ll have your final cart:

      Add and remove products

      By using the useReducer Hook, you kept your main component body well-organized and legible, since the complex logic for parsing and splicing the array is outside of the component. You also could move the reducer outside the componet if you wanted to reuse it, or you can create a custom Hook to use across multiple components. You can make custom Hooks as functions surrounding basic Hooks, such as useState, useReducer, or useEffect.

      Hooks give you the chance to move the stateful logic in and out of the component, as opposed to classes, where you are generally bound to the component. This advantage can extend to other components as well. Since Hooks are functions, you can import them into multiple components rather then using inheritance or other complex forms of class composition.

      In this step, you learned to set state using the current state. You created a component that updated state using both the useState and the useReducer Hooks, and you refactored the component to different Hooks to prevent bugs and improve reusability.

      Conclusion

      Hooks were a major change to React that created a new way to share logic and update components without using classes. Now that you can create components using useState and useReducer, you have the tools to make complex projects that respond to users and dynamic information. You also have a foundation of knowledge that you can use to explore more complex Hooks or to create custom Hooks.

      If you would like to look at more React tutorials, check out our React Topic page, or return to the How To Code in React.js series page.



      Source link

      How To Manage State on React Class Components


      The author selected Creative Commons to receive a donation as part of the Write for DOnations program.

      Introduction

      In React, state refers to a structure that keeps track of how data changes over time in your application. Managing state is a crucial skill in React because it allows you to make interactive components and dynamic web applications. State is used for everything from tracking form inputs to capturing dynamic data from an API. In this tutorial, you’ll run through an example of managing state on class-based components.

      As of the writing of this tutorial, the official React documentation encourages developers to adopt React Hooks to manage state with functional components when writing new code, rather than using class-based components. Although the use of React Hooks is considered a more modern practice, it’s important to understand how to manage state on class-based components as well. Learning the concepts behind state management will help you navigate and troubleshoot class-based state management in existing code bases and help you decide when class-based state management is more appropriate. There’s also a class-based method called componentDidCatch that is not available in Hooks and will require setting state using class methods.

      This tutorial will first show you how to set state using a static value, which is useful for cases where the next state does not depend on the first state, such as setting data from an API that overrides old values. Then it will run through how to set a state as the current state, which is useful when the next state depends on the current state, such as toggling a value. To explore these different ways of setting state, you’ll create a product page component that you’ll update by adding purchases from a list of options.

      Prerequisites

      Step 1 — Creating an Empty Project

      In this step, you’ll create a new project using Create React App. Then you will delete the sample project and related files that are installed when you bootstrap the project. Finally, you will create a simple file structure to organize your components. This will give you a solid basis on which to build this tutorial’s sample application for managing state on class-based components.

      To start, make a new project. In your terminal, run the following script to install a fresh project using create-react-app:

      • npx create-react-app state-class-tutorial

      After the project is finished, change into the directory:

      In a new terminal tab or window, start the project using the Create React App start script. The browser will auto-refresh on changes, so leave this script running while you work:

      You will get a running local server. If the project did not open in a browser window, you can open it with http://localhost:3000/. If you are running this from a remote server, the address will be http://your_domain:3000.

      Your browser will load with a simple React application included as part of Create React App:

      React template project

      You will be building a completely new set of custom components, so you’ll need to start by clearing out some boilerplate code so that you can have an empty project.

      To start, open src/App.js in a text editor. This is the root component that is injected into the page. All components will start from here. You can find more information about App.js at How To Set Up a React Project with Create React App.

      Open src/App.js with the following command:

      You will see a file like this:

      state-class-tutorial/src/App.js

      import React from 'react';
      import logo from './logo.svg';
      import './App.css';
      
      function App() {
        return (
          <div className="App">
            <header className="App-header">
              <img src={logo} className="App-logo" alt="logo" />
              <p>
                Edit <code>src/App.js</code> and save to reload.
              </p>
              <a
                className="App-link"
                href="https://reactjs.org"
                target="_blank"
                rel="noopener noreferrer"
              >
                Learn React
              </a>
            </header>
          </div>
        );
      }
      
      export default App;
      

      Delete the line import logo from './logo.svg';. Then replace everything in the return statement to return a set of empty tags: <></>. This will give you a valid page that returns nothing. The final code will look like this:

      state-class-tutorial/src/App.js

      
      import React from 'react';
      import './App.css';
      
      function App() {
        return <></>;
      }
      
      export default App;
      

      Save and exit the text editor.

      Finally, delete the logo. You won’t be using it in your application and you should remove unused files as you work. It will save you from confusion in the long run.

      In the terminal window type the following command:

      If you look at your browser, you will see a blank screen.

      blank screen in chrome

      Now that you have cleared out the sample Create React App project, create a simple file structure. This will help you keep your components isolated and independent.

      Create a directory called components in the src directory. This will hold all of your custom components.

      Each component will have its own directory to store the component file along with the styles, images, and tests.

      Create a directory for App:

      Move all of the App files into that directory. Use the wildcard, *, to select any files that start with App. regardless of file extension. Then use the mv command to put them into the new directory:

      • mv src/App.* src/components/App

      Next, update the relative import path in index.js, which is the root component that bootstraps the whole process:

      The import statement needs to point to the App.js file in the App directory, so make the following highlighted change:

      state-class-tutorial/src/index.js

      import React from 'react';
      import ReactDOM from 'react-dom';
      import './index.css';
      import App from './components/App/App';
      import * as serviceWorker from './serviceWorker';
      
      ReactDOM.render(
        <React.StrictMode>
          <App />
        </React.StrictMode>,
        document.getElementById('root')
      );
      
      // If you want your app to work offline and load faster, you can change
      // unregister() to register() below. Note this comes with some pitfalls.
      // Learn more about service workers: https://bit.ly/CRA-PWA
      serviceWorker.unregister();
      

      Save and exit the file.

      Now that the project is set up, you can create your first component.

      Step 2 — Using State in a Component

      In this step, you’ll set the initial state of a component on its class and reference the state to display a value. You’ll then make a product page with a shopping cart that displays the total items in the cart using the state value. By the end of the step, you’ll know the different ways to hold a value and when you should use state rather than a prop or a static value.

      Building the Components

      Start by creating a directory for Product:

      • mkdir src/components/Product

      Next, open up Product.js in that directory:

      • nano src/components/Product/Product.js

      Start by creating a component with no state. The component will have two parts: The cart, which has the number of items and the total price, and the product, which has a button to add and remove an item. For now, the buttons will have no actions.

      Add the following code to Product.js:

      state-class-tutorial/src/components/Product/Product.js

      import React, { Component } from 'react';
      import './Product.css';
      
      export default class Product extends Component {
        render() {
          return(
            <div className="wrapper">
              <div>
                Shopping Cart: 0 total items.
              </div>
              <div>Total: 0</div>
      
              <div className="product"><span role="img" aria-label="ice cream">🍦</span></div>
              <button>Add</button> <button>Remove</button>
            </div>
          )
        }
      }
      

      You have also included a couple of div elements that have JSX class names so you can add some basic styling.

      Save and close the file, then open Product.css:

      • nano src/components/Product/Product.css

      Give some light styling to increase the font-size for the text and the emoji:

      state-class-tutorial/src/components/Product/Product.css

      .product span {
          font-size: 100px;
      }
      
      .wrapper {
          padding: 20px;
          font-size: 20px;
      }
      
      .wrapper button {
          font-size: 20px;
          background: none;
      }
      

      The emoji will need a much larger font size than the text, since it’s acting as the product image in this example. In addition, you are removing the default gradient background on buttons by setting the background to none.

      Save and close the file.

      Now, render the Product component in the App component so you can see the results in the browser. Open App.js:

      • nano src/components/App/App.js

      Import the component and render it. You can also delete the CSS import since you won’t be using it in this tutorial:

      state-class-tutorial/src/components/App/App.js

      import React from 'react';
      import Product from '../Product/Product';
      
      function App() {
        return <Product />
      }
      
      export default App;
      

      Save and close the file. When you do, the browser will refresh and you’ll see the Product component.

      Product Page

      Setting the Initial State on a Class Component

      There are two values in your component values that are going to change in your display: total number of items and total cost. Instead of hard coding them, in this step you’ll move them into an object called state.

      The state of a React class is a special property that controls the rendering of a page. When you change the state, React knows that the component is out-of-date and will automatically re-render. When a component re-renders, it modifies the rendered output to include the most up-to-date information in state. In this example, the component will re-render whenever you add a product to the cart or remove it from the cart. You can add other properties to a React class, but they won’t have the same ability to trigger re-rendering.

      Open Product.js:

      • nano src/components/Product/Product.js

      Add a property called state to the Product class. Then add two values to the state object: cart and total. The cart will be an array, since it may eventually hold many items. The total will be a number. After assigning these, replace references to the values with this.state.property:

      state-class-tutorial/src/components/Product/Product.js

      
      import React, { Component } from 'react';
      import './Product.css';
      
      export default class Product extends Component {
      
        state = {
          cart: [],
          total: 0
        }
      
        render() {
          return(
            <div className="wrapper">
              <div>
                Shopping Cart: {this.state.cart.length} total items.
              </div>
              <div>Total {this.state.total}</div>
      
              <div className="product"><span role="img" aria-label="ice cream">🍦</span></div>
              <button>Add</button> <button>Remove</button>
            </div>
          )
        }
      }
      

      Notice that in both cases, since you are referencing JavaScript inside of your JSX, you need to wrap the code in curly braces. You are also displaying the length of the cart array to get a count of the number of items in the array.

      Save the file. When you do, the browser will refresh and you’ll see the same page as before.

      Product Page

      The state property is a standard class property, which means that it is accessible in other methods, not just the render method.

      Next, instead of displaying the price as a static value, convert it to a string using the toLocaleString method, which will convert the number to a string that matches the way numbers are displayed in the browser’s region.

      Create a method called getTotal() that takes the state and converts it to a localized string using an array of currencyOptions. Then, replace the reference to state in the JSX with a method call:

      state-class-tutorial/src/components/Product/Product.js

      import React, { Component } from 'react';
      import './Product.css';
      
      export default class Product extends Component {
      
        state = {
          cart: [],
          total: 0
        }
      
        currencyOptions = {
          minimumFractionDigits: 2,
          maximumFractionDigits: 2,
        }
      
        getTotal = () => {
          return this.state.total.toLocaleString(undefined, this.currencyOptions)
        }
      
        render() {
          return(
            <div className="wrapper">
              <div>
                Shopping Cart: {this.state.cart.length} total items.
              </div>
              <div>Total {this.getTotal()}</div>
      
              <div className="product"><span role="img" aria-label="ice cream">🍦</span></div>
              <button>Add</button> <button>Remove</button>
            </div>
          )
        }
      }
      

      Since total is a price for goods, you are passing currencyOptions that set the maximum and minimum decimal places for your total to two. Note that this is set as a separate property. Often, beginner React developers will put information like this in the state object, but it is best to only add information to state that you expect to change. This way, the information in state will be easier to keep strack of as your application scales.

      Another important change you made was to create the getTotal() method by assigning an arrow function to a class property. Without using the arrow function, this method would create a new this binding, which would interfere with the current this binding and introduce a bug into our code. You’ll see more on this in the next step.

      Save the file. When you do, the page will refresh and you’ll see the value converted to a decimal.

      Price converted to decimal

      You’ve now added state to a component and referenced it in your class. You also accessed values in the render method and in other class methods. Next, you’ll create methods to update the state and show dynamic values.

      Step 3 — Setting State from a Static Value

      So far you’ve created a base state for the component and you’ve referenced that state in your functions and your JSX code. In this step, you’ll update your product page to modify the state on button clicks. You’ll learn how to pass a new object containing updated values to a special method called setState, which will then set the state with the updated data.

      To update state, React developers use a special method called setState that is inherited from the base Component class. The setState method can take either an object or a function as the first argument. If you have a static value that doesn’t need to reference the state, it’s best to pass an object containing the new value, since it’s easier to read. If you need to reference the current state, you pass a function to avoid any references to out-of-date state.

      Start by adding an event to the buttons. If your user clicks Add, then the program will add the item to the cart and update the total. If they click Remove, it will reset the cart to an empty array and the total to 0. For example purposes, the program will not allow a user to add an item more then once.

      Open Product.js:

      • nano src/components/Product/Product.js

      Inside the component, create a new method called add, then pass the method to the onClick prop for the Add button:

      state-class-tutorial/src/components/Product/Product.js

      import React, { Component } from 'react';
      import './Product.css';
      
      export default class Product extends Component {
      
        state = {
          cart: [],
          total: 0
        }
      
        add = () => {
          this.setState({
            cart: ['ice cream'],
            total: 5
          })
        }
      
        currencyOptions = {
          minimumFractionDigits: 2,
          maximumFractionDigits: 2,
        }
      
        getTotal = () => {
          return this.state.total.toLocaleString(undefined, this.currencyOptions)
        }
      
        render() {
          return(
            <div className="wrapper">
              <div>
                Shopping Cart: {this.state.cart.length} total items.
              </div>
              <div>Total {this.getTotal()}</div>
      
              <div className="product"><span role="img" aria-label="ice cream">🍦</span></div>
              <button onClick={this.add}>Add</button>
              <button>Remove</button>
            </div>
          )
        }
      }
      

      Inside the add method, you call the setState method and pass an object containing the updated cart with a single item ice cream and the updated price of 5. Notice that you again used an arrow function to create the add method. As mentioned before, this will ensure the function has the proper this context when running the update. If you add the function as a method without using the arrow function, the setState would not exist without binding the function to the current context.

      For example, if you created the add function this way:

      export default class Product extends Component {
      ...
        add() {
          this.setState({
            cart: ['ice cream'],
            total: 5
          })
        }
      ...
      }
      

      The user would get an error when they click on the Add button.

      Context Error

      Using an arrow function ensures that you’ll have the proper context to avoid this error.

      Save the file. When you do, the browser will reload, and when you click on the Add button the cart will update with the current amount.

      Click on the button and see state updated

      With the add method, you passed both properties of the state object: cart and total. However, you do not always need to pass a complete object. You only need to pass an object containing the properties that you want to update, and everything else will stay the same.

      To see how React can handle a smaller object, create a new function called remove. Pass a new object containing just the cart with an empty array, then add the method to the onClick property of the Remove button:

      state-class-tutorial/src/components/Product/Product.js

      import React, { Component } from 'react';
      import './Product.css';
      
      export default class Product extends Component {
      
        ...
        remove = () => {
          this.setState({
            cart: []
          })
        }
      
        render() {
          return(
            <div className="wrapper">
              <div>
                Shopping Cart: {this.state.cart.length} total items.
              </div>
              <div>Total {this.getTotal()}</div>
      
              <div className="product"><span role="img" aria-label="ice cream">🍦</span></div>
              <button onClick={this.add}>Add</button>
              <button onClick={this.remove}>Remove</button>
            </div>
          )
        }
      }
      

      Save the file. When the browser refreshes, click on the Add and Remove buttons. You’ll see the cart update, but not the price. The total state value is preserved during the update. This value is only preserved for example purposes; with this application, you would want to update both properties of the state object. But you will often have components with stateful properties that have different responsibilities, and you can make them persist by leaving them out of the updated object.

      The change in this step was static. You knew exactly what the values would be ahead of time, and they didn’t need to be recalculated from state. But if the product page had many products and you wanted to be able to add them multiple times, passing a static object would provide no guarantee of referencing the most up-to-date state, even if your object used a this.state value. In this case, you could instead use a function.

      In the next step, you’ll update state using functions that reference the current state.

      Step 4 — Setting State Using Current State

      There are many times when you’ll need to reference a previous state to update a current state, such as updating an array, adding a number, or modifying an object. To be as accurate as possible, you need to reference the most up-to-date state object. Unlike updating state with a predefined value, in this step you’ll pass a function to the setState method, which will take the current state as an argument. Using this method, you will update a component’s state using the current state.

      Another benefit of setting state with a function is increased reliability. To improve performance, React may batch setState calls, which means that this.state.value may not be fully reliable. For example, if you update state quickly in several places, it is possible that a value could be out of date. This can happen during data fetches, form validations, or any situation where several actions are occurring in parallel. But using a function with the most up-to-date state as the argument ensures that this bug will not enter your code.

      To demonstrate this form of state management, add some more items to the product page. First, open the Product.js file:

      • nano src/components/Product/Product.js

      Next, create an array of objects for different products. The array will contain the product emoji, name, and price. Then loop over the array to display each product with an Add and Remove button:

      state-class-tutorial/src/components/Product/Product.js

      import React, { Component } from 'react';
      import './Product.css';
      
      const products = [
        {
          emoji: '🍦',
          name: 'ice cream',
          price: 5
        },
        {
          emoji: '🍩',
          name: 'donuts',
          price: 2.5,
        },
        {
          emoji: '🍉',
          name: 'watermelon',
          price: 4
        }
      ];
      
      export default class Product extends Component {
      
        ...
      
      
        render() {
          return(
            <div className="wrapper">
              <div>
                Shopping Cart: {this.state.cart.length} total items.
              </div>
              <div>Total {this.getTotal()}</div>
              <div>
                {products.map(product => (
                  <div key={product.name}>
                    <div className="product">
                      <span role="img" aria-label={product.name}>{product.emoji}</span>
                    </div>
                    <button onClick={this.add}>Add</button>
                    <button onClick={this.remove}>Remove</button>
                  </div>
                ))}
              </div>
            </div>
          )
        }
      }
      

      In this code, you are using the map() array method to loop over the products array and return the JSX that will display each element in your browser.

      Save the file. When the browser reloads, you’ll see an updated product list:

      Product list

      Now you need to update your methods. First, change the add() method to take the product as an argument. Then instead of passing an object to setState(), pass a function that takes the state as an argument and returns an object that has the cart updated with the new product and the total updated with the new price:

      state-class-tutorial/src/components/Product/Product.js

      import React, { Component } from 'react';
      import './Product.css';
      
      ...
      
      export default class Product extends Component {
      
        state = {
          cart: [],
          total: 0
        }
      
        add = (product) => {
          this.setState(state => ({
            cart: [...state.cart, product.name],
            total: state.total + product.price
          }))
        }
      
        currencyOptions = {
          minimumFractionDigits: 2,
          maximumFractionDigits: 2,
        }
      
        getTotal = () => {
          return this.state.total.toLocaleString(undefined, this.currencyOptions)
        }
      
        remove = () => {
          this.setState({
            cart: []
          })
        }
      
        render() {
          return(
            <div className="wrapper">
              <div>
                Shopping Cart: {this.state.cart.length} total items.
              </div>
              <div>Total {this.getTotal()}</div>
      
              <div>
                {products.map(product => (
                  <div key={product.name}>
                    <div className="product">
                      <span role="img" aria-label={product.name}>{product.emoji}</span>
                    </div>
                    <button onClick={() => this.add(product)}>Add</button>
                    <button onClick={this.remove}>Remove</button>
                  </div>
                ))}
              </div>
            </div>
          )
        }
      }
      

      Inside the anonymous function that you pass to setState(), make sure you reference the argument—state—and not the component’s state—this.state. Otherwise, you still run a risk of getting an out-of-date state object. The state in your function will be otherwise identical.

      Take care not to directly mutate state. Instead, when adding a new value to the cart, you can add the new product to the state by using the spread syntax on the current value and adding the new value onto the end.

      Finally, update the call to this.add by changing the onClick() prop to take an anonymous function that calls this.add() with the relevant product.

      Save the file. When you do, the browser will reload and you’ll be able to add multiple products.

      Adding products

      Next, update the remove() method. Follow the same steps: convert setState to take a function, update the values without mutating, and update the onChange() prop:

      state-class-tutorial/src/components/Product/Product.js

      import React, { Component } from 'react';
      import './Product.css';
      
      ...
      
      export default class Product extends Component {
      
      ...
      
        remove = (product) => {
          this.setState(state => {
            const cart = [...state.cart];
            cart.splice(cart.indexOf(product.name))
            return ({
              cart,
              total: state.total - product.price
            })
          })
        }
      
        render() {
          return(
            <div className="wrapper">
              <div>
                Shopping Cart: {this.state.cart.length} total items.
              </div>
              <div>Total {this.getTotal()}</div>
              <div>
                {products.map(product => (
                  <div key={product.name}>
                    <div className="product">
                      <span role="img" aria-label={product.name}>{product.emoji}</span>
                    </div>
                    <button onClick={() => this.add(product)}>Add</button>
                    <button onClick={() => this.remove(product)}>Remove</button>
                  </div>
                ))}
              </div>
            </div>
          )
        }
      }
      

      To avoid mutating the state object, you must first make a copy of it using the spread operator. Then you can splice out the item you want from the copy and return the copy in the new object. By copying state as the first step, you can be sure that you will not mutate the state object.

      Save the file. When you do, the browser will refresh and you’ll be able to add and remove items:

      Remove items

      There is still a bug in this application: In the remove method, a user can subtract from the total even if the item is not in the cart. If you click Remove on the ice cream without adding it to your cart, your total will be -5.00.

      You can fix the bug by checking for an item’s existence before subtracting, but an easier way is to keep your state object small by only keeping references to the products and not separating references to products and total cost. Try to avoid double references to the same data. Instead, store the raw data in state— in this case the whole product object—then perform the calculations outside of the state.

      Refactor the component so that the add() method adds the whole object, the remove() method removes the whole object, and the getTotal method uses the cart:

      state-class-tutorial/src/components/Product/Product.js

      import React, { Component } from 'react';
      import './Product.css';
      
      ...
      
      export default class Product extends Component {
      
        state = {
          cart: [],
        }
      
        add = (product) => {
          this.setState(state => ({
            cart: [...state.cart, product],
          }))
        }
      
        currencyOptions = {
          minimumFractionDigits: 2,
          maximumFractionDigits: 2,
        }
      
        getTotal = () => {
          const total = this.state.cart.reduce((totalCost, item) => totalCost + item.price, 0);
          return total.toLocaleString(undefined, this.currencyOptions)
        }
      
        remove = (product) => {
          this.setState(state => {
            const cart = [...state.cart];
            const productIndex = cart.findIndex(p => p.name === product.name);
            if(productIndex < 0) {
              return;
            }
            cart.splice(productIndex, 1)
            return ({
              cart
            })
          })
        }
      
        render() {
          ...
        }
      }
      

      The add() method is similar to what it was before, except that reference to the total property has been removed. In the remove() method, you find the index of the product with findByIndex. If the index doesn’t exist, you’ll get a -1. In that case, you use a conditional statement toreturn nothing. By returning nothing, React will know the state didn’t change and won’t trigger a re-render. If you return state or an empty object, it will still trigger a re-render.

      When using the splice() method, you are now passing 1 as the second argument, which will remove one value and keep the rest.

      Finally, you calculate the total using the reduce() array method.

      Save the file. When you do, the browser will refresh and you’ll have your final cart:

      Add and remove

      The setState function you pass can have an additional argument of the current props, which can be helpful if you have state that needs to reference the current props. You can also pass a callback function to setState as the second argument, regardless of if you pass an object or function for the first argument. This is particularly useful when you are setting state after fetching data from an API and you need to perform a new action after the state update is complete.

      In this step, you learned how to update a new state based on the current state. You passed a function to the setState function and calculated new values without mutating the current state. You also learned how to exit a setState function if there is no update in a manner that will prevent a re-render, adding a slight performance enhancement.

      Conclusion

      In this tutorial, you have developed a class-based component with a dynamic state that you’ve updated statically and using the current state. You now have the tools to make complex projects that respond to users and dynamic information.

      React does have a way to manage state with Hooks, but it is helpful to understand how to use state on components if you need to work with components that must be class-based, such as those that use the componentDidCatch method.

      Managing state is key to nearly all components and is necessary for creating interactive applications. With this knowledge you can recreate many common web components, such as sliders, accordions, forms, and more. You will then use the same concepts as you build applications using hooks or develop components that pull data dynamically from APIs.

      If you would like to look at more React tutorials, check out our React Topic page, or return to the How To Code in React.js series page.



      Source link