Lifting State šŸ‹šŸ»ā€ā™€ļø

jorjishasan

Jorjis Hasan

Posted on June 4, 2024

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

šŸ’– šŸ’Ŗ šŸ™… šŸš©
jorjishasan
Jorjis Hasan

Posted on June 4, 2024

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related