Q1. What is lifting state up in React?
Lifting state up is a pattern where you move the shared state to the closest common ancestor of components that need it. Instead of having state in multiple child components, you keep it in the parent and pass it down via props, along with callbacks to update it.
Q2. Why do we lift state up?
To keep multiple components in sync. When two or more components rely on the same data, storing that data in a common parent ensures that all children reflect the same state. This avoids inconsistencies and makes the data flow more predictable.
Q3. Give an example of lifting state up.
Consider two input fields that need to display the same value. Instead of each having its own state, lift the value to their parent. The parent manages the state and passes it as value to both inputs, along with an onChange handler that updates the parent state.
Q4. What are the benefits of lifting state up?
It centralizes the data, making it easier to debug and maintain. It also reduces duplication and ensures a single source of truth. This pattern aligns with React's unidirectional data flow, where data flows down and actions flow up.
Q5. Can lifting state up cause prop drilling?
Yes, if the common ancestor is far away, you may need to pass props through many intermediate components. To mitigate prop drilling, you can use Context API or state management libraries like Redux.
