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:
Accordion
is the parent component here if you see the hierarchy over the picture.We create a state variable
activeIndex
withnull
value at the parent(Accordion
) component. Whynull
? Because by default, no accordion is clicked.We'll give children(
AccordianFrame
) access to modify theactiveIndex
state variable by sharing thesetActiveIndex()
function via props.Now, when any accordion is clicked, it triggers
setActiveIndex()
with its own index value. TheactiveIndex
variable will update accordingly.When it matches the
index === activeIndex, ' the accordion that was clicked will receive the
isActive = true` value through props and be expanded.
Dev View: Live โจ
CODE: GITHUB
File-structures followed here โฌ๏ธ
โโโ src/
โ โโโ AccordionFrame.jsx
โ โโโ App.jsx
โ โโโ constant.jsx
โ โโโ index.css
โโโ tailwind.config.js
โโโ vite.config.js
Top comments (0)