Lifting state up in React is a key feature that most React.js beginners struggle with. It's quite normal for a beginner starting to learn a framework or a new language to struggle with some concept surrounding certain functionalities. With âLifting State Upâ in React.js, it is very handy in building a scalable front-end of an application.
What Does âLifting State Upâ in React.js Mean?
Most beginners in the quest to learn how props works, can easily understand how content(data) is passed from a parent component to its child component. That is very important. But what if you want to do it the other way round, thus passing content from âChild Componentâ to its âParent Componentâ so that the other âChild Componentsâ who are directly related to the parent Component get access to the data. This brings in the concept of âLifting State Upâ. Lifting state up enables you to pass state data generated by a "Child Component" to its closest âParent Componentâ.
We have an âApp Componentâ which renders two child components âExpense Componentâ and âNew Expense Componentâ. The âNew Expense Componentâ generates some states by fetching some user input. Usually, in an application, you use a form to generate data but you might not need it in that component, instead, we use the data in another component, in our case the âExpense Componentâ which displays all the expenses generated in our âNew Expense Componentâ.
In a React.js application, if two components are not directly related, you cannot pass data generated between the two components. For example in our demo app, data cannot be shared between âNew Expense Componentâ and âExpense Componentâ. We can only communicate from child to parent and from parent to child.
To be able to communicate between these two components, the data needs to pass through the closest parent which has access to these two child components. The App Component in our case has direct access to both the âNew Expense Componentâ and the âExpense Componentâ. So now we can pass our generated state data from âNew Expense Componentâ to the âApp Componentâ.
Then subsequently pass the state data generated by the âNew Expense â to the âExpense Dataâ through the âApp Componentâ. We do this utilizing props.