Sharing State Across Components in React
Course: React JS Training
Topic: Sharing State Across Components, Lifting State Up, Props, and Component Synchronization
Learning Objective: Understand how to share data between React components, manage common state in a parent component, and keep multiple components synchronized using state and props.
Course Links: JustAcademy React JS Training | Register for React JS Course Demo
1. Introduction to Sharing State Across Components
In React, applications are divided into reusable components. Each component can display information, receive user input, and manage its own state. However, sometimes multiple components need access to the same information or must update together. In such situations, sharing state across components becomes important.
For example, consider a shopping application where a product list displays an Add to Cart button and a navigation bar displays the total number of items in the cart. Both components need access to the same cart information. If each component maintains a separate copy of the cart state, their displayed values may become inconsistent.
React solves this problem by allowing developers to move shared state to a common parent component and pass the required information and event handlers to child components through props. This approach is commonly called lifting state up.
Key Concepts
- State: Data that a component remembers and can update over time.
- Props: Read-only values passed from a parent component to a child component.
- Lifting State Up: Moving state from child components to their closest common parent.
- Shared State: State managed in one place and used by multiple components.
- Single Source of Truth: Keeping one authoritative owner for each piece of shared state.
2. What Does Sharing State Across Components Mean?
Sharing state across components means storing information in a place where multiple components can use it and ensuring that updates are reflected consistently in the relevant parts of the interface.
In a typical React application, a parent component can maintain the shared state and pass its current value and update functions to its children.
Example Scenario
Imagine a page containing two components:
- CounterDisplay: Displays the current count.
- CounterControls: Contains buttons to increase or decrease the count.
If both components need to work with the same count, the count should be stored in a common parent. The parent passes the count to CounterDisplay and passes the update functions to CounterControls.
Component Structure
App
├── CounterDisplay
│ └── Receives count through props
└── CounterControls
└── Receives update functions through props
When the user clicks a button, CounterControls calls a function provided by App. App updates its state, and React re-renders the components that use the updated value.
3. Understanding Lifting State Up
Lifting state up is one of the most common techniques for sharing state in React. It involves moving state from individual child components into their closest common parent component.
Why Is Lifting State Up Needed?
Suppose two components each maintain their own state for the same information. Updating one component does not automatically update the other because their state values are independent.
By moving the state into a common parent, both components can receive the same value and remain synchronized.
Steps to Lift State Up
- Identify the components that need to share information.
- Find their closest common parent component.
- Move the shared state into that parent component.
- Pass the current state to child components using props.
- Pass event handler functions to children so they can request state updates.
- Update the shared state in the parent when users interact with the interface.
Example: Independent State
import { useState } from 'react';
function CounterOne() {
const [count, setCount] = useState(0);
return (
<button onClick={() => setCount(count + 1)}>
Counter One: {count}
</button>
);
}
function CounterTwo() {
const [count, setCount] = useState(0);
return (
<button onClick={() => setCount(count + 1)}>
Counter Two: {count}
</button>
);
}
export default function App() {
return (
<>
<CounterOne />
<CounterTwo />
</>
);
}
Explanation: Each counter has its own state. Clicking Counter One does not change Counter Two because they maintain separate values.
Example: Shared State Through a Parent
import { useState } from 'react';
function CounterDisplay({ count }) {
return <h2>Current Count: {count}</h2>;
}
function CounterControls({ onIncrease, onDecrease }) {
return (
<div>
<button onClick={onIncrease}>Increase</button>
<button onClick={onDecrease}>Decrease</button>
</div>
);
}
export default function App() {
const [count, setCount] = useState(0);
function increaseCount() {
setCount(currentCount => currentCount + 1);
}
function decreaseCount() {
setCount(currentCount => currentCount - 1);
}
return (
<div>
<CounterDisplay count={count} />
<CounterControls
onIncrease={increaseCount}
onDecrease={decreaseCount}
/>
</div>
);
}
Explanation: App owns the count state. CounterDisplay receives the value, while CounterControls receives functions that update it. Both child components work with the same shared state.
4. Role of Props in Sharing State
Props allow components to communicate with one another through the component hierarchy. A parent can pass data and callback functions to a child component.
Passing State as Props
function UserProfile({ username }) {
return <h2>Welcome, {username}!</h2>;
}
function App() {
const username = "Rahul";
return <UserProfile username={username} />;
}
export default App;
In this example, the parent passes username to UserProfile. The child uses the received value to display the user's name.
Passing Event Handlers as Props
function Child({ onMessage }) {
return (
<button onClick={onMessage}>
Send Message
</button>
);
}
function App() {
function handleMessage() {
alert("Message received from child!");
}
return <Child onMessage={handleMessage} />;
}
export default App;
The parent defines the function and passes it to the child. The child calls the function when the button is clicked. This pattern allows child components to trigger updates managed by their parent.
Important Rules
- Props are read-only from the receiving component's perspective.
- A child should not directly modify the parent's state variable.
- A child can call a callback supplied by the parent to request an update.
- Data normally flows from parent to child through props.
5. Sharing State Between Sibling Components
Sibling components are components rendered by the same parent. React does not automatically share their local state. To coordinate them, the common parent should own the shared state.
Example: Sharing a Message Between Siblings
import { useState } from 'react';
function MessageInput({ message, onMessageChange }) {
return (
<input
type="text"
value={message}
onChange={event => onMessageChange(event.target.value)}
placeholder="Enter a message"
/>
);
}
function MessagePreview({ message }) {
return <p>Preview: {message || "Your message will appear here"}</p>;
}
export default function App() {
const [message, setMessage] = useState("");
return (
<div>
<h2>Shared Message Example</h2>
<MessageInput
message={message}
onMessageChange={setMessage}
/>
<MessagePreview message={message} />
</div>
);
}
How It Works
- The App component creates the message state using useState.
- MessageInput receives the current message and a callback.
- When the user types, MessageInput calls the callback with the new text.
- App updates its message state.
- MessagePreview receives the updated message and displays it.
Result: Typing in one component automatically updates the content shown in the other component.
6. Controlled and Uncontrolled Components
When sharing state, developers often distinguish between controlled and uncontrolled components. These terms describe where a component's important values are managed.
| Feature |
Controlled Component |
Uncontrolled Component |
| Value management |
Important value is provided through props. |
Important value is generally maintained internally. |
| Who controls behavior? |
Parent component can determine the value. |
Component manages its own behavior. |
| Coordination |
Useful for synchronizing multiple components. |
Convenient for independent behavior. |
| Example |
Input with value and onChange props. |
Input using a ref to read its DOM value. |
Controlled Input Example
import { useState } from 'react';
function App() {
const [email, setEmail] = useState("");
return (
<div>
<label htmlFor="email">Email:</label>
<input
id="email"
value={email}
onChange={event => setEmail(event.target.value)}
/>
<p>Entered email: {email}</p>
</div>
);
}
export default App;
The email input is controlled because React state determines its value. Every change updates the state, which then supplies the latest value to the input.
7. Sharing State Across Components Using Context API
Passing props works well when components are close together. However, when many nested components need the same data, passing props through every intermediate component can become inconvenient. This is often called prop drilling.
React Context provides another way to make information available to components deeper in the component tree without manually passing it through every intermediate component.
When to Consider Context
- Theme settings used by many components.
- Current user information used across pages.
- Language or localization preferences.
- Application-wide settings.
Basic Context Example
import { createContext, useContext, useState } from 'react';
const ThemeContext = createContext("light");
function ThemeDisplay() {
const theme = useContext(ThemeContext);
return <p>Current theme: {theme}</p>;
}
function App() {
const [theme, setTheme] = useState("light");
function toggleTheme() {
setTheme(currentTheme =>
currentTheme === "light" ? "dark" : "light"
);
}
return (
<ThemeContext value={theme}>
<ThemeDisplay />
<button onClick={toggleTheme}>Toggle Theme</button>
</ThemeContext>
);
}
export default App;
React version note: The example uses the React 19 context-provider syntax, <ThemeContext value={theme}>. In React 18 and earlier, use <ThemeContext.Provider value={theme}> instead.
When the theme changes, the context provider supplies the updated value and components consuming that context can render the new theme.
Important: Context is not necessary for every shared value. For a small group of related components, lifting state up and passing props is often simpler.
8. Sharing State Across Distant Components
Sometimes, two components that need the same information are far apart in the component tree. There are several possible approaches, depending on the application's size and complexity.
| Approach |
How It Works |
Best Use Case |
| Lifting state up |
Moves shared state to a common parent and passes props. |
Related components with a nearby common parent. |
| Context API |
Makes a value available to descendant components. |
Shared data needed by many nested components. |
| State management library |
Provides structured ways to manage shared application state. |
Larger applications with complex state requirements. |
| URL state |
Stores relevant navigation or filter state in URL parameters. |
Search filters, pagination, and shareable page views. |
State should be placed as close as practical to the components that need it. Choose a broader state-sharing solution only when the application's requirements justify it.
9. Real-World Example: Shopping Cart
In an e-commerce application, the product list and cart summary often need access to the same cart information. The parent component can maintain the cart state and pass the cart count and event handlers to the relevant children.
import { useState } from 'react';
function Product({ onAddToCart }) {
return (
<div>
<h3>Wireless Headphones</h3>
<button onClick={onAddToCart}>Add to Cart</button>
</div>
);
}
function CartSummary({ cartCount }) {
return <h2>Cart Items: {cartCount}</h2>;
}
export default function App() {
const [cartCount, setCartCount] = useState(0);
function addToCart() {
setCartCount(count => count + 1);
}
return (
<div>
<h1>Online Store</h1>
<CartSummary cartCount={cartCount} />
<Product onAddToCart={addToCart} />
</div>
);
}
Expected Behavior
- The initial cart count is zero.
- Clicking Add to Cart increases the shared count.
- The CartSummary component displays the latest count.
- The count remains consistent because it has one owner.
This example illustrates the basic pattern. A complete shopping cart would usually store product identifiers, quantities, and other product details in an array or object rather than only a number.
10. Best Practices for Sharing State
- Choose a suitable state owner: Store shared state in the closest common parent that can coordinate all components that need it.
- Avoid duplicate state: Do not maintain separate copies of the same shared information unless they intentionally represent different things.
- Pass focused props: Give each child only the values and callbacks it needs.
- Keep data flow clear: Pass data down and use callback props to request changes upward.
- Use functional updates when appropriate: For updates based on the previous value, use the setter callback form, such as
setCount(count => count + 1).
- Avoid unnecessary global state: Not every state variable belongs in Context or a global store.
- Keep state minimal: Avoid storing values that can be calculated from existing state or props.
- Update objects and arrays immutably: Create new objects or arrays instead of modifying existing state directly.
- Use Context selectively: It is useful when many descendants need the same value, but it does not replace every use of local state or props.
- Keep components reusable: Prefer receiving values and callbacks through props when that makes a component easier to reuse.
11. Common Mistakes and Their Solutions
| Mistake |
Why It Causes Problems |
Solution |
| Maintaining duplicate shared state |
Components can display inconsistent values. |
Move the shared state to a common owner. |
| Trying to modify props |
Props are read-only inputs. |
Call a callback supplied by the parent. |
| Forgetting to pass a callback |
The child has no way to request the intended update. |
Pass the correct handler as a prop. |
| Calling a handler while rendering |
The function runs immediately instead of waiting for a click. |
Use onClick={handleClick} or an appropriate arrow function. |
| Mutating state directly |
React may not detect the intended update correctly, and existing data may be corrupted. |
Use state setters with new values or immutable updates. |
| Using Context for every value |
It can make dependencies harder to understand. |
Prefer local state and props when they are sufficient. |
| Storing derived data unnecessarily |
Multiple values may drift out of sync. |
Calculate derived values during rendering when practical. |
12. Advantages of Sharing State Across Components
- Consistent UI: Multiple components can reflect the same current information.
- Less duplication: One component owns shared data rather than several components maintaining copies.
- Better coordination: Components can respond to the same user action.
- Improved maintainability: Shared update logic is easier to locate and manage.
- Reusable components: Components can receive data and behavior through props instead of depending on hidden internal state.
- Predictable data flow: State ownership and update paths are clearer.
13. Limitations and Challenges
- Passing many props through multiple levels can lead to prop drilling.
- Moving state too high in the tree can make component dependencies unnecessarily broad.
- Changing shared state may cause multiple consumers to re-render.
- Complex shared state may require more structured update logic.
- Incorrect state ownership can make components harder to reuse or test.
These challenges can often be addressed by choosing the right state owner, keeping state minimal, splitting components thoughtfully, and introducing Context or a state management library only when needed.
14. Mini Project: Shared Task Tracker
Project Objective: Build a small task tracker where one component adds tasks and another displays the task list. Both components use the same state stored in their common parent.
Complete Example
import { useState } from 'react';
function TaskForm({ onAddTask }) {
const [task, setTask] = useState("");
function handleSubmit(event) {
event.preventDefault();
const trimmedTask = task.trim();
if (!trimmedTask) {
return;
}
onAddTask(trimmedTask);
setTask("");
}
return (
<form onSubmit={handleSubmit}>
<input
value={task}
onChange={event => setTask(event.target.value)}
placeholder="Enter a task"
/>
<button type="submit">Add Task</button>
</form>
);
}
function TaskList({ tasks }) {
if (tasks.length === 0) {
return <p>No tasks added yet.</p>;
}
return (
<ul>
{tasks.map((task, index) => (
<li key={`${task}-${index}`}>{task}</li>
))}
</ul>
);
}
export default function App() {
const [tasks, setTasks] = useState([]);
function addTask(newTask) {
setTasks(currentTasks => [...currentTasks, newTask]);
}
return (
<div>
<h1>Shared Task Tracker</h1>
<TaskForm onAddTask={addTask} />
<TaskList tasks={tasks} />
<p>Total Tasks: {tasks.length}</p>
</div>
);
}
Project Explanation
- The App component owns the tasks array.
- TaskForm stores the text currently being entered into its own local state.
- After submission, TaskForm calls onAddTask with the new task.
- App adds the new task to the shared array using an immutable update.
- TaskList receives the updated array through props and displays each task.
- The total task count is calculated directly from the shared array.
Learning Outcome: This project demonstrates how local state and shared state can work together. The form input has local state because it belongs to TaskForm, while the task collection is shared and belongs to App.
15. Interview Questions and Answers
Q1. What is sharing state across components in React?
Answer: It is the practice of making the same state available to multiple components so that they can display consistent information and coordinate their behavior.
Q2. What is lifting state up?
Answer: Lifting state up means moving state from child components into their closest common parent and passing the required values and event handlers back down through props.
Q3. Why is lifting state up useful?
Answer: It allows related components to use a shared value, prevents unnecessary duplication, and keeps their behavior synchronized.
Q4. Can a child component directly change its parent's state?
Answer: No. A child should not directly modify the parent's state. The parent can pass a callback function that the child calls to request an update.
Q5. What are props in React?
Answer: Props are read-only inputs that allow a component to receive data and functions from its parent.
Q6. What is a controlled component?
Answer: A controlled component receives an important value through props, with its behavior determined by the component managing that value.
Q7. What is prop drilling?
Answer: Prop drilling occurs when props are passed through several intermediate components that may not use the data themselves, just to reach a deeper component.
Q8. How can Context help share state?
Answer: Context makes a value available to descendant components without requiring every intermediate component to pass it through props.
Q9. Should all React state be stored in one parent component?
Answer: No. Each piece of state should live in an appropriate owner. Keep local state near the component that uses it and lift only the state that needs to be shared.
Q10. What is the single source of truth?
Answer: It means each piece of shared information has one authoritative owner, reducing conflicting or duplicated state.
Q11. How do sibling components share information?
Answer: Their closest common parent can own the shared state and pass values and update callbacks to both siblings.
Q12. What is the difference between state and props?
Answer: State is managed by the component that owns it and can be updated through React state setters. Props are inputs received from a parent and should be treated as read-only.
16. Practice Exercises
- Create two counter buttons that update the same count displayed by a parent.
- Create a text input whose value is displayed in a separate sibling component.
- Build an accordion where opening one panel closes the previously opened panel.
- Create a product list and a cart summary that share cart information.
- Build a theme switcher that updates several components using lifted state.
- Refactor a component with duplicated state so that one common parent manages the shared value.
- Build a task tracker where a form adds items to a list owned by the parent.
Self-Assessment Checklist
- Can you explain state and props?
- Can you identify the closest common parent of two components?
- Can you lift state up using useState?
- Can you pass data and callback functions through props?
- Can you synchronize sibling components?
- Can you distinguish local state from shared state?
- Can you explain when Context may be useful?
- Can you avoid duplicate state and direct state mutation?
17. Important Summary
Sharing state across components is an essential React concept for building interactive and consistent user interfaces. When multiple components need the same information, store that information in an appropriate shared owner and pass it to the components that need it.
- Use
useState to manage changing data.
- Lift shared state to the closest common parent when sibling components need to coordinate.
- Use props to pass state values and callback functions to children.
- Keep one authoritative owner for each piece of shared state.
- Use Context when many descendant components need access to the same value.
- Keep independent state local to the component that owns it.
Understanding these techniques will help you create reusable components, avoid inconsistent data, and build React applications that are easier to maintain.
18. Official Learning Resources
Conclusion
Sharing state across components helps React applications maintain consistent information across different parts of the interface. By understanding lifting state up, props, callback functions, controlled components, and Context, developers can choose the right way to coordinate component behavior. Start with local state, lift it to a common parent when necessary, and introduce broader state-sharing techniques as the application grows.