One place for hosting & domains

      How To Manage State in React with Redux


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

      Introduction

      Redux is a popular data store for JavaScript and React applications. It follows a central principle that data binding should flow in one direction and should be stored as a single source of truth. Redux gained popularity because of the simplicity of the design concept and the relatively small implementation.

      Redux operates according to a few concepts. First, the store is a single object with fields for each selection of data. You update the data by dispatching an action that says how the data should change. You then interpret actions and update the data using reducers. Reducers are functions that apply actions to data and return a new state, instead of mutating the previous state.

      In small applications, you may not need a global data store. You can use a mix of local state and context to manage state. But as your application scales, you may encounter situations where it would be valuable to store information centrally so that it will persist across routes and components. In that situation, Redux will give you a standard way to store and retrieve data in an organized manner.

      In this tutorial, you’ll use Redux in a React application by building a bird watching test application. Users will be able to add birds they have seen and increment a bird each time they see it again. You’ll build a single data store, and you’ll create actions and reducers to update the store. You’ll then pull data into your components and dispatch new changes to update the data.

      Prerequisites

      • You will need a development environment running Node.js; this tutorial was tested on Node.js version 10.22.0 and npm version 6.14.6. To install this on macOS or Ubuntu 18.04, follow the steps in How to Install Node.js and Create a Local Development Environment on macOS or the Installing Using a PPA section of How To Install Node.js on Ubuntu 18.04.

      • A React development environment set up with Create React App, with the non-essential boilerplate removed. To set this up, follow Step 1 — Creating an Empty Project of the How To Manage State on React Class Components tutorial. This tutorial will use redux-tutorial as the project name.

      • You will be using React components, Hooks, and forms in this tutorial, including the useState Hook and custom Hooks. You can learn about components and Hooks in our tutorials How To Manage State with Hooks on React Components and How To Build Forms in React.

      • You will also need a basic knowledge of JavaScript, HTML, and CSS, which you can find in our How To Build a Website With HTML series, How To Build a Website With CSS series, and in How To Code in JavaScript.

      Step 1 — Setting Up a Store

      In this step, you’ll install Redux and connect it to your root component. You’ll then create a base store and show the information in your component. By the end of this step, you’ll have a working instance of Redux with information displaying in your components.

      To start, install redux and react-redux. The package redux is framework agnostic and will connect your actions and reducers. The package react-redux contains the bindings to run a Redux store in a React project. You’ll use code from react-redux to send actions from your components and to pull data from the store into your components.

      Use npm to install the two packages with the following command:

      • npm install --save redux react-redux

      When the component is finished installing, you’ll receive output like this. Your output may be slightly different:

      Output

      ... + redux@4.0.5 + react-redux@7.2.1 added 2 packages from 1 contributor, updated 1 package and audited 1639 packages in 20.573s

      Now that you have the packages installed, you need to connect Redux to your project. To use Redux, you’ll need to wrap your root components with a Provider to ensure that the store is available to all child components in the tree. This is similar to how you would add a Provider using React’s native context.

      Open src/index.js:

      Import the Provider component from the react-redux package. Add the Provider to your root component around any other components by making the following highlighted changes to your code:

      redux-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';
      import { Provider } from 'react-redux';
      
      ReactDOM.render(
        <React.StrictMode>
          <Provider>
            <App />
          </Provider>
        </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();
      

      Now that you have wrapped your components, it’s time to add a store. The store is your central collection of data. In the next step, you’ll learn to create reducers that will set the default values and update your store, but for now you will hard-code the data.

      Import the createStore function from redux, then pass a function that returns an object. In this case, return an object with a field called birds that points to an array of individual birds. Each bird will have a name and a views count. Save the output of the function to a value called store, then pass the store to a prop called store in the Provider:

      redux-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';
      import { Provider } from 'react-redux';
      import { createStore } from 'redux';
      
      const store = createStore(() => ({
        birds: [
          {
            name: 'robin',
            views: 1
          }
        ]
      }));
      
      ReactDOM.render(
        <React.StrictMode>
          <Provider store={store}>
            <App />
          </Provider>
        </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 close the file. Now that you have some data, you need to be able to display it. Open src/components/App/App.js:

      • nano src/components/App/App.js

      Like with context, every child component will be able to access the store without any additional props. To access items in your Redux store, use a Hook called useSelector from the react-redux package. The useSelector Hook takes a selector function as an argument. The selector function will receive the state of your store as an argument that you will use to return the field you want:

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

      import React from 'react';
      import { useSelector } from 'react-redux';
      import './App.css';
      
      function App() {
        const birds = useSelector(state => state.birds);
      
        return <></>
      }
      
      export default App;
      

      Since useSelector is a custom Hook, the component will re-render whenever the Hook is called. That means that the data—birds—will always be up to date.

      Now that you have the data, you can display it in an unordered list. Create a surrounding <div> with a className of wrapper. Inside, add a <ul> element and loop over the birds array with map(), returning a new <li> item for each. Be sure to use the bird.name as a key:

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

      import React from 'react';
      import { useSelector } from 'react-redux'
      import './App.css';
      
      function App() {
        const birds = useSelector(state => state.birds);
      
        return (
          <div className="wrapper">
            <h1>Bird List</h1>
            <ul>
              {birds.map(bird => (
                <li key={bird.name}>
                  <h3>{bird.name}</h3>
                  <div>
                    Views: {bird.views}
                  </div>
                </li>
              ))}
            </ul>
          </div>
        );
      }
      
      export default App;
      

      Save the file. Once the file is saved, the browser will reload and you’ll find your bird list::

      List of birds

      Now that you have a basic list, add in the rest of the components you’ll need for your bird watching app. First, add a button to increment the views after the list of views:

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

      import React from 'react';
      import { useSelector } from 'react-redux'
      import './App.css';
      
      function App() {
        const birds = useSelector(state => state.birds);
      
        return (
          <div className="wrapper">
            <h1>Bird List</h1>
            <ul>
              {birds.map(bird => (
                <li key={bird.name}>
                  <h3>{bird.name}</h3>
                  <div>
                    Views: {bird.views}
                    <button><span role="img" aria-label="add">➕</span></button>
                  </div>
                </li>
              ))}
            </ul>
          </div>
        );
      }
      
      export default App;
      

      Next, create a <form> with a single <input> before the bird list so a user can add in a new bird. Be sure to surround the <input> with a <label> and to add a type of submit to the add button to make sure everything is accessible:

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

      import React from 'react';
      import { useSelector } from 'react-redux'
      import './App.css';
      
      function App() {
        const birds = useSelector(state => state.birds);
      
        return (
          <div className="wrapper">
            <h1>Bird List</h1>
            <form>
              <label>
                <p>
                  Add Bird
                </p>
                <input type="text" />
              </label>
              <div>
                <button type="submit">Add</button>
              </div>
            </form>
            <ul>
              {birds.map(bird => (
                <li key={bird.name}>
                  <h3>{bird.name}</h3>
                  <div>
                    Views: {bird.views}
                    <button><span role="img" aria-label="add">➕</span></button>
                  </div>
                </li>
              ))}
            </ul>
          </div>
        );
      }
      
      export default App;
      

      Save and close the file. Next, open up App.css to add some styling:

      • nano src/components/App/App.css

      Add some padding to the wrapper class. Then capitalize the h3 element, which holds the bird name. Finally, style the buttons. Remove the default button styles on the add <button> and then add a margin to the form <button>.

      Replace the file’s contents with the following:

      redux-tutorial/src/components/App/App.css

      
      .wrapper {
          padding: 20px;
      }
      
      .wrapper h3 {
          text-transform: capitalize;
      }
      
      .wrapper form button {
          margin: 10px 0;
          cursor: pointer;
      }
      
      .wrapper ul button {
          background: none;
          border: none;
          cursor: pointer;
      }
      

      Additionally, give each button a cursor of pointer, which will change the cursor when hovering over the button to indicate to the user that the button is clickable.

      Save and close the file. When you do the browser will refresh with your components:

      Bird watching app with form

      The buttons and form are not connected to any actions yet, and so can not interact with the Redux store. You’ll add the actions in Step 2 and connect them in Step 3.

      In this step, you installed Redux and created a new store for your application. You connected the store to your application using Provider and accessed the elements inside your components using the useSelector Hook.

      In the next step, you’ll create actions and reducers to update your store with new information.

      Step 2 — Creating Actions and Reducers

      Next, you’ll create actions to add a bird and to increment a view. You’ll then make a reducer that will update the information depending on the action type. Finally, you’ll use the reducers to create a default store using combineReducers.

      Actions are the message you send to the data store with the intended change. Reducers take those messages and update the shared store by applying the changes depending on the action type. Your components will send the actions they want your store to use, and your reducers will use actions to update the data in the store. You never call reducers directly, and there are cases where one action may impact several reducers.

      There are many different options for organizing your actions and reducers. In this tutorial, you’ll organize by domain. That means your actions and reducers will be defined by the type of feature they will impact.

      Create a directory called store:

      This directory will contain all of your actions and reducers. Some patterns store them alongside components, but the advantage here is that you have a separate point of reference for the shape of the whole store. When a new developer enters the project, they will be able to read the structure of the store at a glance.

      Make a directory called birds inside the store directory. This will contain the actions and reducers specifically for updating your bird data:

      Next, open up a file called birds.js so that you can start to add actions and reducers. If you have a large number of actions and reducers you may want to split them into separate files, such as birds.actions.js and birds.reducers.js, but when there are only a few it can be easier to read when they are in the same location:

      • nano src/store/birds/birds.js

      First, you are going to create actions. Actions are the messages that you send from a component to your store using a method called dispatch, which you’ll use in the next step.

      An action must return an object with a type field. Otherwise, the return object can include any additional information you want to send.

      Create a function called addBirds that takes a bird as an argument and returns an object containing a type of 'ADD_BIRD' and the bird as a field:

      redux-tutorial/src/store/birds/birds.js

      export function addBird(bird) {
        return {
          type: 'ADD_BIRD',
          bird,
        }
      }
      

      Notice that you are exporting the function so that you can later import and dispatch it from your component.

      The type field is important for communicating with reducers, so by convention most Redux stores will save the type to a variable to protect against misspelling.

      Create a const called ADD_BIRD that saves the string 'ADD_BIRD'. Then update the action:

      redux-tutorial/src/store/birds/birds.js

      const ADD_BIRD = 'ADD_BIRD';
      
      export function addBird(bird) {
        return {
          type: ADD_BIRD,
          bird,
        }
      }
      

      Now that you have an action, create a reducer that will respond to the action.

      Reducers are functions that will determine how a state should change based on actions. The actions don’t make changes themselves; the reducers will take the state and make changes based on actions.

      A reducer receives two arguments: the current state and the action. The current state refers to the state for a particular section of the store. Generally, the name of the reducer will match with a field in the store. For example, suppose you had a store shaped like this:

      {
        birds: [
          // collection of bird objects
        ],
        gear: {
          // gear information
        }
      }
      

      You would create two reducers: birds and gear. The state for the birds reducer will be the array of birds. The state for the gear reducer would be the object containing the gear information.

      Inside birds.js create a reducer called birds that takes state and action and returns the state without any changes:

      redux-tutorial/src/store/birds/birds.js

      const ADD_BIRD = 'ADD_BIRD';
      
      export function addBird(bird) {
        return {
          type: ADD_BIRD,
          bird,
        }
      }
      
      function birds(state, action) {
        return state;
      }
      

      Notice that you are not exporting the reducer. You will not use the reducer directly and instead will combine them into a usable collection that you will export and use to create your base store in index.js. Notice also that you need to return the state if there are no changes. Redux will run all the reducers anytime you dispatch an action, so if you don’t return state you risk losing your changes.

      Finally, since Redux returns the state if there are no changes, add a default state using default parameters.

      Create a defaultBirds array that will have the placeholder bird information. Then update the state to include defaultBirds as the default parameter:

      redux-tutorial/src/store/birds/birds

      const ADD_BIRD = 'ADD_BIRD';
      
      export function addBird(bird) {
        return {
          type: ADD_BIRD,
          bird,
        }
      }
      
      const defaultBirds = [
        {
          name: 'robin',
          views: 1,
        }
      ];
      
      function birds(state=defaultBirds, action) {
        return state;
      }
      

      Now that you have a reducer returning your state, you can use the action to apply the changes. The most common pattern is to use a switch on the action.type to apply changes.

      Create a switch statement that will look at the action.type. If the case is ADD_BIRD, spread out the current state into a new array and add the bird with a single view:

      redux-tutorial/src/store/birds/birds.js

      const ADD_BIRD = 'ADD_BIRD';
      
      export function addBird(bird) {
        return {
          type: ADD_BIRD,
          bird,
        }
      }
      
      const defaultBirds = [
        {
          name: 'robin',
          views: 1,
        }
      ];
      
      function birds(state=defaultBirds, action) {
        switch (action.type) {
          case ADD_BIRD:
            return [
              ...state,
              {
                name: action.bird,
                views: 1
              }
            ];
          default:
            return state;
        }
      }
      

      Notice that you are returning the state as the default value. More importantly, you are not mutating state directly. Instead, you are creating a new array by spreading the old array and adding a new value.

      Now that you have one action, you can create an action for incrementing a view.

      Create an action called incrementBird. Like the addBird action, this will take a bird as an argument and return an object with a type and a bird. The only difference is the type will be 'INCREMENT_BIRD':

      redux-tutorial/src/store/birds/birds.js

      const ADD_BIRD = 'ADD_BIRD';
      const INCREMENT_BIRD = 'INCREMENT_BIRD';
      
      export function addBird(bird) {
        return {
          type: ADD_BIRD,
          bird,
        }
      }
      
      export function incrementBird(bird) {
        return {
          type: INCREMENT_BIRD,
          bird
        }
      }
      
      const defaultBirds = [
        {
          name: 'robin',
          views: 1,
        }
      ];
      
      function birds(state=defaultBirds, action) {
        switch (action.type) {
          case ADD_BIRD:
            return [
              ...state,
              {
                name: action.bird,
                views: 1
              }
            ];
          default:
            return state;
        }
      }
      

      This action is separate, but you will use the same reducer. Remember, the actions convey the change you want to make on the data and the reducer applies those changes to return a new state.

      Incrementing a bird involves a bit more than adding a new bird. Inside of birds add a new case for INCREMENT_BIRD. Then pull the bird you need to increment out of the array using find() to compare each name with the action.bird:

      redux-tutorial/src/store/bird/birds.js

      const ADD_BIRD = 'ADD_BIRD';
      ...
      function birds(state=defaultBirds, action) {
        switch (action.type) {
          case ADD_BIRD:
            return [
              ...state,
              {
                name: action.bird,
                views: 1
              }
            ];
          case INCREMENT_BIRD:
            const bird = state.find(b => action.bird === b.name);
            return state;
          default:
            return state;
        }
      }
      

      You have the bird you need to change, but you need to return a new state containing all the unchanged birds as well as the bird you’re updating. Select all remaining birds with state.filter by selecting all birds with a name that does not equal action.name. Then return a new array by spreading the birds array and adding the bird at the end:

      redux-tutorial/src/store/bird/birds.js

      const ADD_BIRD = 'ADD_BIRD';
      ...
      
      function birds(state=defaultBirds, action) {
        switch (action.type) {
          case ADD_BIRD:
            return [
              ...state,
              {
                name: action.bird,
                views: 1
              }
            ];
          case INCREMENT_BIRD:
            const bird = state.find(b => action.bird === b.name);
            const birds = state.filter(b => action.bird !== b.name);
            return [
              ...birds,
              bird,
            ];
          default:
            return state;
        }
      }
      

      Finally, update the bird by creating a new object with an incremented view:

      redux-tutorial/src/store/bird/birds.js

      const ADD_BIRD = 'ADD_BIRD';
      ...
      function birds(state=defaultBirds, action) {
        switch (action.type) {
          case ADD_BIRD:
            return [
              ...state,
              {
                name: action.bird,
                views: 1
              }
            ];
          case INCREMENT_BIRD:
            const bird = state.find(b => action.bird === b.name);
            const birds = state.filter(b => action.bird !== b.name);
            return [
              ...birds,
              {
                ...bird,
                views: bird.views + 1
              }
            ];
          default:
            return state;
        }
      }
      

      Notice that you are not using the reducers to sort the data. Sorting could be considered a view concern since the view displays the information to a user. You could have one view that sorts by name and one view that sorts by view count, so it’s better to let individual components handle the sorting. Instead, keep reducers focused on updating the data, and the component focused on converting the data to a usable view for a user.

      This reducer is also imperfect since you could add birds with the same name. In a production app you would need to either validate before adding or give birds a unique id so that you could select the bird by id instead of name.

      Now you have two complete actions and a reducer. The final step is to export the reducer so that it can initialize the store. In the first step, you created the store by passing a function that returns an object. You will do the same thing in this case. The function will take the store and the action and then pass the specific slice of the store to the reducers along with the action. It would look something like this:

      export function birdApp(store={}, action) {
          return {
              birds: birds(store.birds, action)
          }
      }
      

      To simplify things, Redux has a helper function called combineReducers that combines the reducers for you.

      Inside of birds.js, import combineReducers from redux. Then call the function with birds and export the result:

      redux-tutorial/src/store/bird/birds.js

      import { combineReducers } from 'redux';
      const ADD_BIRD = 'ADD_BIRD';
      const INCREMENT_BIRD = 'INCREMENT_BIRD';
      
      export function addBird(bird) {
        return {
          type: ADD_BIRD,
          bird,
        }
      }
      
      export function incrementBird(bird) {
        return {
          type: INCREMENT_BIRD,
          bird
        }
      }
      
      const defaultBirds = [
        {
          name: 'robin',
          views: 1,
        }
      ];
      
      function birds(state=defaultBirds, action) {
        switch (action.type) {
          case ADD_BIRD:
            return [
              ...state,
              {
                name: action.bird,
                views: 1
              }
            ];
          case INCREMENT_BIRD:
            const bird = state.find(b => action.bird === b.name);
            const birds = state.filter(b => action.bird !== b.name);
            return [
              ...birds,
              {
                ...bird,
                views: bird.views + 1
              }
            ];
          default:
            return state;
        }
      }
      
      const birdApp = combineReducers({
        birds
      });
      
      export default birdApp;
      

      Save and close the file.

      Your actions and reducers are all set up. The final step is to initialize your store using the combined reducers instead of a placeholder function.

      Open src/index.js:

      Import the birdApp from birds.js. Then initialize the store using birdApp:

      redux-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';
      import { Provider } from 'react-redux'
      import { createStore } from 'redux'
      import birdApp from './store/birds/birds';
      
      const store = createStore(birdApp);
      
      ReactDOM.render(
        <React.StrictMode>
          <Provider store={store}>
            <App />
          </Provider>
        </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 close the file. When you do the browser will refresh with your application:

      Bird watching app with form

      In this step you created actions and reducers. You learned how to create actions that return a type and how to build reducers that use the action to build and return a new state based on the action. Finally, you combined the reducers into a function that you used to initialize the store.

      Your Redux store is now all set up and ready for changes. In the next step you’ll dispatch actions from a component to update the data.

      Step 3 — Dispatching Changes in a Component

      In this step, you’ll import and call your actions from your component. You’ll use a method called dispatch to send the action and you’ll dispatch the actions inside of event handlers for the form and the button.

      By the end of this step, you’ll have a working application that combines a Redux store and your custom components. You’ll be able to update the Redux store in real time and will be able to display the information in your component as it changes.

      Now that you have working actions, you need to connect them to your events so that you can update the store. The method you will use is called dispatch and it sends a particular action to the Redux store. When Redux receives an action you have dispatched, it will pass the action to the reducers and they will update the data.

      Open App.js:

      • nano src/components/App/App.js

      Inside of App.js import the Hook useDispath from react-redux. Then call the function to create a new dispatch function:

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

      import React from 'react';
      import { useDispatch, useSelector } from 'react-redux'
      import './App.css';
      
      function App() {
        ...
      }
      
      export default App;
      

      Next you’ll need to import your actions. Remember, actions are functions that return an object. The object is what you will ultimately pass into the dispatch function.

      Import incrementBird from the store. Then create an onClick event on the button. When the user clicks on the button, call incrementBird with bird.name and pass the result to dispatch. To make things more readable, call the incrementBird function inside of dispatch:

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

      import React from 'react';
      import { useDispatch, useSelector } from 'react-redux'
      import { incrementBird } from '../../store/birds/birds';
      import './App.css';
      
      function App() {
        const birds = useSelector(state => state.birds);
        const dispatch = useDispatch();
      
        return (
          <div className="wrapper">
            <h1>Bird List</h1>
            <form>
              <label>
                <p>
                  Add Bird
                </p>
                <input type="text" />
              </label>
              <div>
                <button type="submit">Add</button>
              </div>
            </form>
            <ul>
              {birds.map(bird => (
                <li key={bird.name}>
                  <h3>{bird.name}</h3>
                  <div>
                    Views: {bird.views}
                    <button onClick={() => dispatch(incrementBird(bird.name))}><span role="img" aria-label="add">➕</span></button>
                  </div>
                </li>
              ))}
            </ul>
          </div>
        );
      }
      
      export default App;
      

      Save the file. When you do, you’ll be able to increment the robin count:

      Increment a bird

      Next, you need to dispatch the addBird action. This will take two steps: saving the input to an internal state and triggering the dispatch with onSubmit.

      Use the useState Hook to save the input value. Be sure to convert the input to a controlled component by setting the value on the input. Check out the tutorial How To Build Forms in React for a more in-depth look at controlled components.

      Make the following changes to your code:

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

      import React, { useState } from 'react';
      import { useDispatch, useSelector } from 'react-redux'
      import { incrementBird } from '../../store/birds/birds';
      import './App.css';
      
      function App() {
        const [birdName, setBird] = useState('');
        const birds = useSelector(state => state.birds);
        const dispatch = useDispatch();
      
        return (
          <div className="wrapper">
            <h1>Bird List</h1>
            <form>
              <label>
                <p>
                  Add Bird
                </p>
                <input
                  type="text"
                  onChange={e => setBird(e.target.value)}
                  value={birdName}
                />
              </label>
              <div>
                <button type="submit">Add</button>
              </div>
            </form>
            <ul>
              ...
            </ul>
          </div>
        );
      }
      
      export default App;
      

      Next, import addBird from birds.js, then create a function called handleSubmit. Inside the handleSubmit function, prevent the page form submission with event.preventDefault, then dispatch the addBird action with the birdName as an argument. After dispatching the action, call setBird('') to clear the input. Finally, pass handleSubmit to the onSubmit event handler on the form:

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

      import React, { useState } from 'react';
      import { useDispatch, useSelector } from 'react-redux'
      import { addBird, incrementBird } from '../../store/birds/birds';
      import './App.css';
      
      function App() {
        const [birdName, setBird] = useState('');
        const birds = useSelector(state => state.birds);
        const dispatch = useDispatch();
      
        const handleSubmit = event => {
          event.preventDefault();
          dispatch(addBird(birdName))
          setBird('');
        };
      
        return (
          <div className="wrapper">
            <h1>Bird List</h1>
            <form onSubmit={handleSubmit}>
              <label>
                <p>
                  Add Bird
                </p>
                <input
                  type="text"
                  onChange={e => setBird(e.target.value)}
                  value={birdName}
                />
              </label>
              <div>
                <button type="submit">Add</button>
              </div>
            </form>
            <ul>
              {birds.map(bird => (
                <li key={bird.name}>
                  <h3>{bird.name}</h3>
                  <div>
                    Views: {bird.views}
                    <button onClick={() => dispatch(incrementBird(bird.name))}><span role="img" aria-label="add">➕</span></button>
                  </div>
                </li>
              ))}
            </ul>
          </div>
        );
      }
      
      export default App;
      

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

      Save new bird

      You are now calling your actions and updating your birds list in the store. Notice that when your application refreshed you lost the previous information. The store is all contained in memory and so a page refresh will wipe the data.

      This list order will also change if you increment a bird higher in the list.

      Robin goes to the bottom on reorder

      As you saw in Step 2, your reducer is not concerned with sorting the data. To prevent an unexpected change in the components, you can sort the data in your component. Add a sort() function to the birds array. Remember that sorting will mutate the array and you never want to mutate the store. Be sure to create a new array by spreading the data before sorting:

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

      import React, { useState } from 'react';
      import { useDispatch, useSelector } from 'react-redux'
      import { addBird, incrementBird } from '../../store/birds/birds';
      import './App.css';
      
      function App() {
        const [birdName, setBird] = useState('');
        const birds = [...useSelector(state => state.birds)].sort((a, b) => {
          return a.name.toLowerCase() > b.name.toLowerCase() ? 1 : -1;
        });
        const dispatch = useDispatch();
      
        const handleSubmit = event => {
          event.preventDefault();
          dispatch(addBird(birdName))
          setBird('');
        };
      
        return (
          <div className="wrapper">
            <h1>Bird List</h1>
            <form onSubmit={handleSubmit}>
              <label>
                <p>
                  Add Bird
                </p>
                <input
                  type="text"
                  onChange={e => setBird(e.target.value)}
                  value={birdName}
                />
              </label>
              <div>
                <button type="submit">Add</button>
              </div>
            </form>
            <ul>
              {birds.map(bird => (
                <li key={bird.name}>
                  <h3>{bird.name}</h3>
                  <div>
                    Views: {bird.views}
                    <button onClick={() => dispatch(incrementBird(bird.name))}><span role="img" aria-label="add">➕</span></button>
                  </div>
                </li>
              ))}
            </ul>
          </div>
        );
      }
      
      export default App;
      

      Save the file. When you do, the components will stay in alphabetical order as you increment birds.

      Cardinal stays on top

      It’s important to not try and do too much in your Redux store. Keep the reducers focused on maintaining up-to-date information then pull and manipulate the data for your users inside the component.

      Note: In this tutorial, notice that there is a fair amount of code for each action and reducer. Fortunately, there is an officially supported project called Redux Toolkit that can help you reduce the amount of boilerplate code. The Redux Toolkit provides an opinionated set of utilities to quickly create actions and reducers, and will also let you create and configure your store with less code.

      In this step, you dispatched your actions from a component. You learned how to call actions and how to send the result to a dispatch function, and you connected them to event handlers on your components to create a fully interactive store. Finally, you learned how to maintain a consistent user experience by sorting the data without directly mutating the store.

      Conclusion

      Redux is a popular single store. It can be advantageous when working with components that need a common source of information. However, it is not always the right choice in all projects. Smaller projects or projects with isolated components will be able to use built-in state management and context. But as your applications grow in complexity, you may find that central storage is critical to maintaining data integrity. In such cases, Redux is an excellent tool to create a single unified data store that you can use across your components with minimal effort.

      If you would like to read 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 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