DEV Community

Cover image for Lifting State πŸ‹πŸ»β€β™€οΈ
Jorjis Hasan
Jorjis Hasan

Posted on

Lifting State πŸ‹πŸ»β€β™€οΈ

WHY ?

Think of an online grocery store containing 100,000+ products. Each product has a common feature, which is the toggle feature. They will show certain things on click. To function that feature in React, each product must have a state variable. Now, the popup question is, if 100,000 products have 100,000 state variables, would our app be efficient? And what about MILLION?

The answer is BIG NO ❌.

βœ… What if there is just one state variable instead of 100,000 ? That state would be at the top of the parent component. When any product is clicked, only that product will get a share of the state variable and enable the toggle feature.

Doesn't it sound like solution? Yes, the Lifting state does that solution. Well, now you know the lifting state in theory. Let's give it a technical shot!


Before diving deep into State lifting, give it a well-read (controlled & uncontrolled components).

These 2 things are the same :

  • Lifting State
  • State Sharing

Lifting up state is a technique used in React to share states between multiple components. Instead of each component having its own local state, the state is lifted up to their closest ancestor. This common ancestor then passes the state down to the components via props.


Let it make easy steps for you to understand this example illustration:

  1. Accordion is the parent component here if you see the hierarchy over the picture.

  2. We create a state variable activeIndex with null value at the parent(Accordion) component. Why null? Because by default, no accordion is clicked.

  3. We'll give children(AccordianFrame) access to modify the activeIndex state variable by sharing the setActiveIndex() function via props.

  4. Now, when any accordion is clicked, it triggers setActiveIndex() with its own index value. The activeIndex variable will update accordingly.

  5. When it matches the index === activeIndex, ' the accordion that was clicked will receive theisActive = true` value through props and be expanded.

Dev View: Live ✨

Developer VIEW

CODE: GITHUB

File-structures followed here ⬇️


β”œβ”€β”€ src/
β”‚ β”œβ”€β”€ AccordionFrame.jsx
β”‚ β”œβ”€β”€ App.jsx
β”‚ β”œβ”€β”€ constant.jsx
β”‚ β”œβ”€β”€ index.css
β”œβ”€β”€ tailwind.config.js
└── vite.config.js

Top comments (0)