Monday, March 14, 2022

Understanding "Lifting State Up" in React - Example Tutorial

Introduction

If you have ever worked with React, then you know the importance of state management. The state is managed within the component and decides the component’s behavior. But as the application grows, the state is required to be shared among the different components. For such global state sharing, third-party libraries such as Redux are used.


Apart from managing the state inside a component or using redux for the global state, there is one more way to work with the state. This is called “lifting state up”. In this article, we will discuss what is “lifting state up” in React with the help of an example. 


Lifting state up

In React, it is recommended to make a common pattern while using the same state in multiple components. “Lifting state up” is a common pattern used in React to share state among multiple components to avoid complex and unnecessary patterns for state management.  


Understanding "Lifting State Up" in React - Example Tutorial



Observe the following components. 


ListCount:


const ListCount = () => {

  return <div>Total count: </div>;

};

 

export default ListCount;



ListShow:


import { useState } from "react";

 

const ListShow = () => {

  const [list, setList] = useState([]);

  return (

    <div>

      {list.length > 0

        ? list.map((item) => {

            <li key={item}>{item}</li>;

          })

        : null}

    </div>

  );

};

export default ListShow;




AddToList:


import {AddToList} from 'react'

 

const AddToList = () => {

    const [value, setValue] = useState("")

    return (

        <div>

            <form onSubmit={}>

                <input type="text" value={value} onChange={(e)=>{setValue(e.target.value)}}/>

                <button>Add</button>

            </form>

        </div>

    )

}

 

export default AddToList


The “AddToList” component will add the value to the list while the “ListShow” displays the entire list. Moreover, “ListCount” displays the total amount of items in the list. What is common in these components? Each of them requires to share the same state, i.e. the list. 


  • In the “ListCount”, list is required to count its length.
  • In the “ListShow”, list is to be displayed. 
  • In the “AddToList”, list is to be updated with the new value. 


So one way is to use the state in every component and another is by “lifting state up”.


For “lifting state up”, we need to create the state in the common ancestor of all the three components. And the common ancestor is the “App” component. 


import "./App.css";

import AddToList from "./AddToList";

import ListCount from "./ListCount";

import ListShow from "./ListShow";

 

const App = () => {

  return (

    <div className="App">

      <ListCount />

      <AddToList />

      <ListShow />

    </div>

  );

};

 

export default App;


Let’s add the state to the componentone the ,


const App = () => {

  const [list, setList] = useState([]);

  return (

    <div className="App">

      <ListCount list={list} />

      <ListShow list={list} />

      <AddToList />

    </div>

  );

};


“list” is required in “ListCount” and “ListShow”. So it is passed as props to both the components. Let’s use it in them


ListCount:


const ListCount = ({ list }) => {

  return <div>Total count: {list.length} </div>;

};

 

export default ListCount;


ListShow:


 

const ListShow = ({ list }) => {

  return (

    <div>

      {list.length > 0

        ? list.map((item) => {

            return <li key={item}>{item}</li>;

          })

        : null}

    </div>

  );

};

export default ListShow;


In the “AddToList” components, we need to update the list. So we can send, the “setList” method as props to it. 


import { useState } from "react";

 

const AddToList = ({ setList }) => {

  const [value, setValue] = useState("");

 

  const submitHandler = (e) => {

    e.preventDefault();

    setList((prevList) => {

      return [...prevList, value];

    });

 

    setValue("");

  };

 

  return (

    <div>

      <form onSubmit={submitHandler}>

        <input

          type="text"

          value={value}

          onChange={(e) => {

            setValue(e.target.value);

          }}

        />

        <button>Add</button>

      </form>

    </div>

  );

};

 

export default AddToList;



The “AddToList” component is adding a new value to the list by using the “setList” method that is received as props. 


What did we do in this application? We could have used the state, i.e. “list” in each of the three components in one way or another. It would have worked fine as well. But using such as way could have led to problems in the future because we are using a mismanaged pattern for the state. Instead, we lifted the state up to the common ancestor and passed it to the required components in a better pattern. This is called “lifting state up”.


Wrapping it up

So “Lifting State Up” is a common pattern used by React developers to create a better pattern for sharing states among components. In this pattern, the state is lifted up to the common ancestor, and then, it is shared among the components as required. Though “Lifting State Up” is a simple concept, but is very helpful, and React developers are recommended to keep it in mind while using state. 


Other React.js  Articles and Tutorials you may like

Thanks for reading this article so far. If you like this React tutorial about lifecycle methods, please share it with your friends and colleagues. IF you have any questions or feedback, then please ask in comments. 

No comments:

Post a Comment

Feel free to comment, ask questions if you have any doubt.