Hello! In our last lesson, we dove deep into the crucial patterns for updating array and object state immutably. You learned that to trigger a re-render, you must always provide a new object or array to your state setter function, using techniques like the spread syntax (...), .map(), and .filter().
So far, all the state we've managed has lived inside a single component. But in any real application, you'll quickly face a new challenge: what happens when separate, sibling components need to share or synchronize the same data? How does an "Add to Cart" button in one component update the total in a separate "Cart Summary" component?
This lesson answers that exact question. Our goal is to master one of the most fundamental patterns in React: lifting state up to a common ancestor to share state between sibling components. This technique is the primary method for making different components communicate and work together in a coordinated way.
The Problem: Independent, Siloed State
Imagine two components, ComponentA and ComponentB, that are rendered side-by-side by a parent component.
<Parent>
<ComponentA />
<ComponentB />
</Parent>
If both ComponentA and ComponentB declare their own useState, their states are completely independent and private. ComponentA has no idea what the state of ComponentB is, and vice-versa. There is no direct way for them to communicate. This is by design—it's called encapsulation—but it presents a problem when their states need to be synchronized.
The Solution: Lifting State Up
The solution is elegant: when you want to coordinate multiple components, you find their closest common parent component. You then "lift" the state from the children up into that parent.
The process involves these key steps:
- Remove state from the child components.
- Move the state (the
useStatecall) into the common parent component. This parent now "owns" the state and becomes the single source of truth. - Pass the state down to the children via props.
- Pass event handlers (functions that update the state) down to the children via props. This allows the children to tell the parent when to update the state.
Let's walk through this process with the official React documentation, which provides a crystal-clear example using an accordion UI.
Sharing State Between Components
The official React documentation offers a foundational, step-by-step guide to lifting state up. It introduces the problem and methodically walks through the solution, establishing key terminology along the way.
Please read from the beginning of the article up to and including 'Step 3: Add state to the common parent'. Focus on the three-step process and how the Panel and Accordion components are transformed.
From JavaScript to TypeScript: A Practical Example
The react.dev example perfectly illustrates the pattern. Now, let's solidify this by seeing it in a TypeScript context, which involves defining the types for the props being passed down.
The following article uses a "confirm email" form, another classic use case where two sibling inputs need to be aware of each other's values for validation.
This article from omarileon.me provides a concise, practical walkthrough of lifting state up, but with TypeScript code. It reinforces the same pattern you just read about.
Read the article from the beginning down to (but not including) the 'Conclusion'. Note how the EmailInput component is refactored from having its own state to receiving email and onInputChange as props, complete with TypeScript type definitions.
Synthesizing the Pattern in TypeScript
Let's combine what we've learned and write the Accordion example from react.dev in TypeScript.
First, we define the props for our Panel component. It no longer manages its own isActive state. Instead, it receives isActive as a prop, and it also receives a function onShow to call when its button is clicked.
// Panel.tsx
interface PanelProps {
title: string;
children: React.ReactNode;
isActive: boolean;
onShow: () => void; // A function that takes no arguments and returns nothing
}
export function Panel({ title, children, isActive, onShow }: PanelProps) {
return (
<section className="panel">
<h3>{title}</h3>
{isActive ? (
<p>{children}</p>
) : (
<button onClick={onShow}>Show</button>
)}
</section>
);
}
Next, the Accordion parent component owns the state. Instead of each panel having a boolean isActive state, the parent has a single piece of state, activeIndex, which tracks which panel is currently open.
// Accordion.tsx
import { useState } from 'react';
import { Panel } from './Panel';
export function Accordion() {
// State is lifted up to the common parent
const [activeIndex, setActiveIndex] = useState<number>(0);
return (
<>
<h2>Almaty, Kazakhstan</h2>
<Panel
title="About"
// The child's active status is determined by the parent's state
isActive={activeIndex === 0}
// The parent passes down a function to update its own state
onShow={() => setActiveIndex(0)}
>
With a population of about 2 million, Almaty is Kazakhstan's largest city.
</Panel>
<Panel
title="Etymology"
isActive={activeIndex === 1}
onShow={() => setActiveIndex(1)}
>
The name comes from <span lang="kk-KZ">алма</span>, the Kazakh word for "apple".
</Panel>
</>
);
}

Controlled vs. Uncontrolled Components
This pattern introduces two important terms for describing components.
- Uncontrolled Component: A component that manages its own state internally. Our original
Panelwith its ownisActivestate was uncontrolled. - Controlled Component: A component that receives its state and behavior via props from a parent. Our final
Panelcomponent is controlled by theAccordion. HTML form elements like<input>are another classic example: an input is controlled if itsvalueandonChangehandler are provided by a parent React component.
Understanding this distinction is key to component design. Controlled components offer maximum flexibility and allow parents to coordinate them, while uncontrolled components are often simpler to use in isolation.
Sharing State Between Components
The react.dev article you read earlier contains a 'Deep Dive' section that formally defines these two important terms. It's a short but very important read for understanding component design.
Please read the 'Deep Dive' section on 'Controlled and uncontrolled components'.
Seeing it in Action: A Video Walkthrough
To see this entire process in a live-coding format, the following video builds a simple shopping cart and runs into the exact problem we've been discussing.
React 19 Tutorial - 26 - Sharing State Between Components
This video from Codevolution provides an excellent end-to-end demonstration of identifying the need for shared state and refactoring by lifting it up.
Watch the full video. Pay attention to how the ProductCard and CartSummary components are initially out of sync, and how moving the cartItems state to the parent ShoppingCart component resolves the issue.
Test your understanding!
You are building a temperature converter. You have two inputs, one for Celsius and one for Fahrenheit. When the user types a value in the Celsius input, the Fahrenheit input should update with the converted value, and vice-versa.
Here are the conversion formulas:
- Fahrenheit to Celsius:
(f - 32) * 5 / 9 - Celsius to Fahrenheit:
(c * 9 / 5) + 32
You have a TemperatureInput component:
// TemperatureInput.tsx
interface TemperatureInputProps {
scale: 'c' | 'f';
// What other props does this component need?
}
export function TemperatureInput({ scale }: TemperatureInputProps) {
// How does this component get its value and handle changes?
const scaleNames = {
c: 'Celsius',
f: 'Fahrenheit'
};
return (
<fieldset>
<legend>Enter temperature in {scaleNames[scale]}:</legend>
<input /> {/* How do we wire this up? */}
</fieldset>
);
}
Your task is to design the Calculator parent component that renders two TemperatureInput components and makes them stay in sync by lifting state up. Describe the state you would keep in Calculator and the props you would pass to each TemperatureInput.
Show answer
The key is that you only need to store one piece of state: the current temperature. Storing it in Celsius is a good choice.
-
State in
Calculator:
You'll hold the temperature in Celsius and the current input text. Let's simplify and just store the temperature in one scale, say Celsius.const [temperature, setTemperature] = useState<string>(''); // Store as string to handle empty input const [scale, setScale] = useState<'c' | 'f'>('c');When the scale is 'c',
temperatureis in Celsius. When it's 'f',temperatureis in Fahrenheit. -
Props for
TemperatureInput:
TheTemperatureInputneeds to be a controlled component. It needs the current temperature value and a function to call when its value changes.interface TemperatureInputProps { scale: 'c' | 'f'; temperature: string; onTemperatureChange: (temperature: string) => void; } -
The
CalculatorComponent:// Calculator.tsx import { useState } from 'react'; // ... helper functions for conversion ... export function Calculator() { const [temperature, setTemperature] = useState(''); const [scale, setScale] = useState<'c'|'f'>('c'); const handleCelsiusChange = (temp: string) => { setScale('c'); setTemperature(temp); }; const handleFahrenheitChange = (temp: string) => { setScale('f'); setTemperature(temp); }; const celsius = scale === 'f' ? tryConvert(temperature, toCelsius) : temperature; const fahrenheit = scale === 'c' ? tryConvert(temperature, toFahrenheit) : temperature; return ( <div> <TemperatureInput scale="c" temperature={celsius} onTemperatureChange={handleCelsiusChange} /> <TemperatureInput scale="f" temperature={fahrenheit} onTemperatureChange={handleFahrenheitChange} /> </div> ); }This is a classic implementation. The parent holds the most recently edited value and scale. It then calculates the value for both inputs and passes them down. When a child input changes, it calls the handler, which updates the parent's state, triggering a re-render and synchronizing the other input.
Conclusion
You've now learned one of the most powerful and frequently used patterns in React. By lifting state up, you can transform a collection of isolated components into a fully interactive and synchronized user interface.
Key Takeaways:
- Single Source of Truth: For any data that changes in your application, there should be a single component that "owns" it.
- Lift State to the Common Ancestor: When sibling components need to share data, move that state to their closest common parent.
- Data Flows Down, Events Flow Up: The parent passes state down to its children via props. The children communicate back up to the parent by invoking function props (event handlers).
- Controlled Components: This pattern results in children becoming "controlled components," whose behavior is dictated by the props they receive from their parent.
Next Steps
We have now thoroughly covered how to manage state that is local to your UI with the useState hook. However, many real-world applications need to interact with systems outside of React, such as fetching data from a server, setting up timers, or directly manipulating the browser DOM. These operations are known as side effects.
In our next lesson, we will introduce a new hook, useEffect, and explain what side effects are and why they need to be handled outside of your component's main rendering logic. This will open up a whole new world of possibilities for what your React applications can do.