React
/Intermediate
Sibling Communication
Definition
React components cannot communicate directly with their siblings. They must use "Lifting State Up" to pass data to their common parent, which then passes the data down to the other sibling.
Explain Like I'm New
Two siblings are in separate rooms. They can't hear each other through the walls. If Sibling A wants to tell Sibling B something, Sibling A has to use the walkie-talkie to call Mom (Parent), and then Mom walks into Sibling B's room and delivers the message.
Real World Example
You have a `<Sidebar>` with a list of categories, and a `<ProductList>` showing items. When you click a category in the Sidebar, it tells the `<MainLayout>` (parent), which then passes the `activeCategoryId` down to the `<ProductList>` (sibling).
Common Use Cases
- •Synchronizing two UI components on the same screen (like a Nav bar and a Main Content area)
- •Master-Detail view patterns
Interactive Example
import React, { useState } from "react"; // Sibling A function Controls({ onColorChange }) { return ( <div className="p-4 border"> <h3>Controls (Sibling A)</h3> <button onClick={() => onColorChange("red")}>Red</button> <button onClick={() => onColorChange("blue")}>Blue</button> </div> ); } // Sibling B function Display({ color }) { return ( <div className="p-4 border"> <h3>Display (Sibling B)</h3> <div style={{ width: 100, height: 100, background: color }}></div> </div> ); } // The Common Parent export default function App() { // 1. Lift state to the common parent const [boxColor, setBoxColor] = useState("gray"); return ( <div className="flex gap-4"> {/* 2. Sibling A talks UP to the parent */} <Controls onColorChange={setBoxColor} /> {/* 3. Parent talks DOWN to Sibling B */} <Display color={boxColor} /> </div> ); }
Interview Questions
basic
- Can Sibling A directly call a function inside Sibling B?
- What is the standard React pattern for sibling communication?
intermediate
- What is the performance drawback of lifting state to a common parent?
- If Sibling A updates the parent state, does Sibling A also re-render?
advanced
- How can you communicate between siblings without re-rendering the parent? (Hint: Global state or Event Emitters)
trick
- Can you use a React `ref` to let one sibling control another directly?