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)