Table of contents
No headings in the article.
So often we come across managing state which is arguably the hardest part of any application. It's why there are so many state management libraries available and even some built on top of others.
Let take an example of creating a component componentA which is responsible of displaying and increasing the count on click of a button.
So looking at above code gist we can see a single component can manage its own state but we still need state management libraries if we need those state to any other component or to other parts of the app. Isn't it ?
Hmm well not exactly
So having a single element of state managed in a single component is easy, but what do you do when I need to share that state across components? For example, what if I wanted to do this:
As we know, every component in React has its own state. Because of this sometimes data can be redundant and inconsistent. The count is managed inside , now I need a state management library to access that count value from the and pass it in and update it Well you don't any other state managing libraries but react's own Lifting State Up
So, by Lifting up the state we make the state of the parent component as a single source of truth and pass the data of the parent in its children.
Lifting state up is a common pattern that is essential for React developers to know. It helps you avoid more complex (and often unnecessary) patterns for managing your state.
Lets apply and lift up the state.
We lift up state to a common ancestor of components that need it, so that they can all share in the state. This allows us to more easily share state among all of these components that need rely upon it.
Conclusion
Lifting state up is an important pattern for React developers because sometimes we have state that's located within a particular component that also needs to be shared with sibling components.
Instead of using an entire state management library like Redux or React Context, we can just lift the state up to the closest common ancestor and pass both the state variables the state values down as well as any callbacks to update that state.
#usecontext #redux #react #state #lifting #statemanagement