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)