Lifting State Up Between Siblings
Lifting State Up Between Siblings
1. The Sibling Communication Problem
In React's unidirectional data flow, data flows strictly top-down from parent to child. Sibling components cannot directly communicate with one another or pass state horizontally.
Consider a common scenario:
- Component A: An
AccordionHeaderor aSearchInput - Component B: An
AccordionContentor aSearchResultsList
If Component A holds state in its own local useState, Component B has no way of reading that state or reacting to its changes.
2. The Solution: Lifting State Up
To share state between two or more sibling components:
- 1Identify the closest common parent component in the tree.
- 2Move the state up into that common parent.
- 3Pass the state down to the consuming child as a read-only prop.
- 4Pass an event handler callback down to the modifying child so it can request state changes in the parent.
3. Step-by-Step Code Walkthrough
Step 1: Create the Child Components
Child 1 (SearchInput) receives the current search term and a callback:
Child 2 (SearchResults) receives the filtered list:
Step 2: Lift State to the Common Parent
The parent component (CourseDirectory) owns the query state and coordinates data flow:
4. Single Source of Truth
Lifting state up establishes a single source of truth. Instead of trying to keep local copies of data synchronized across multiple sibling components, one component acts as the authority. This architectural discipline prevents out-of-sync UI states and simplifies debugging.
Practice Quiz
Handling Synthetic Events in React
Continue learning with hands-on practice, examples, and exercises in the upcoming topic.
Related Lessons
| Previous Lesson | Next Lesson |
|---|---|
| Updating State and Immutable Updates | Handling Synthetic Events in React |
Practice Quiz
Test your understanding of this lesson with 5 questions. Each question has one correct answer.