Popular Searches
Popular Course Categories
Popular Courses

Sharing State Between Components

Sharing State Between Components

State Management with useState

Sharing State Between Components in React JS

Course: React JS Training

Topic: Sharing State Between Components

Official Documentation: React – Sharing State Between Components


1. Introduction to Sharing State Between Components

In React JS, components are independent and reusable building blocks of a user interface. Each component can have its own state, but sometimes multiple components need access to the same information. Sharing state between components allows them to display and update data consistently.

For example, consider a shopping application where one component displays a product, another component displays its price, and a third component displays the total amount. If multiple components depend on the same data, managing that data in a common parent component can help keep the interface synchronized.

React commonly uses a technique called Lifting State Up to share state between related components. In this approach, state is moved from individual child components to their closest common parent, and the parent passes the state and event handler functions to its children through props.

2. What Is State in React JS?

State is data that a React component remembers between renders. It can store values such as numbers, strings, arrays, objects, Boolean values, and other information required by the component.

The useState() Hook is used to create state in functional components.

Syntax:

const [state, setState] = useState(initialValue);
  • state: The current state value.
  • setState: The function used to request a state update.
  • useState(): The React Hook used to initialize state.
  • initialValue: The initial value assigned to the state.

Example:

import { useState } from "react";

function Counter() {
  const [count, setCount] = useState(0);

  return (
    <div>
      <h2>Count: {count}</h2>
      <button onClick={() => setCount(count + 1)}>
        Increase
      </button>
    </div>
  );
}

export default Counter;

In this example, the counter component manages its own state. When the button is clicked, the state changes and React updates the displayed count.

3. Why Is Sharing State Between Components Important?

Sharing state is important when multiple components need to work with the same information. Without a shared state source, components may maintain separate copies of the same data, which can become inconsistent.

Common use cases include:

  • Synchronizing multiple input fields.
  • Managing shopping cart items and totals.
  • Controlling tabs and accordion panels.
  • Sharing selected products between components.
  • Updating a user profile from multiple interface sections.
  • Filtering a list using a search component.
  • Managing application settings used by multiple components.
  • Keeping a selected category synchronized with displayed products.

4. Understanding the Parent-Child Component Relationship

React applications often use a component hierarchy. A parent component can render one or more child components. The parent can pass information to its children through props.

Example:

function Parent() {
  return (
    <div>
      <h1>Parent Component</h1>
      <Child />
    </div>
  );
}

function Child() {
  return <p>Child Component</p>;
}

export default Parent;

Here, the Parent component renders the Child component. The parent can pass data and functions to the child by adding props to the Child component.

5. What Are Props in React?

Props, short for properties, are values passed from one component to another. They allow parent components to communicate information to child components.

Example:

function Welcome(props) {
  return <h2>Welcome, {props.name}!</h2>;
}

function App() {
  return (
    <div>
      <Welcome name="Rahul" />
      <Welcome name="Priya" />
    </div>
  );
}

export default App;

Output:

Welcome, Rahul!
Welcome, Priya!

In this example, the parent passes a different name prop to each Welcome component. Props are read-only from the child's perspective. To change shared state, a child can call a callback function supplied by the parent.

6. What Is Lifting State Up?

Lifting State Up is a React technique in which state is moved from child components to their closest common parent component. The parent becomes responsible for managing that shared state and passes the required values to its children through props.

This approach helps multiple components display consistent information and coordinate their behavior.

Basic Structure:

Parent Component
    |
    |-- Shared State
    |
    |-- Child Component A
    |
    |-- Child Component B

The parent owns the shared state. Child components receive state values as props and can request changes by calling event handler functions passed down by the parent.

7. Sharing State Between Two Components

Consider two components that need to display the same message. Instead of storing separate message states in each child, the parent can store the message once and pass it to both children.

Example:

import { useState } from "react";

function MessageOne({ message }) {
  return <h3>Component One: {message}</h3>;
}

function MessageTwo({ message }) {
  return <h3>Component Two: {message}</h3>;
}

function App() {
  const [message, setMessage] = useState("Hello React");

  return (
    <div>
      <MessageOne message={message} />
      <MessageTwo message={message} />
      <button onClick={() => setMessage("State Updated")}>
        Update Message
      </button>
    </div>
  );
}

export default App;

Explanation:

  • The App component stores the message in state.
  • MessageOne receives the message through props.
  • MessageTwo receives the same message through props.
  • Clicking the button updates the parent state.
  • Both child components display the updated message when React renders them again.

8. Passing State from Parent to Child

Passing state from parent to child is one of the most common ways to share data in React. The parent provides the state value through a prop, and the child reads that value when rendering.

Example:

function UserDetails({ name, age }) {
  return (
    <div>
      <h2>Name: {name}</h2>
      <p>Age: {age}</p>
    </div>
  );
}

function App() {
  const user = {
    name: "Manish",
    age: 25
  };

  return <UserDetails name={user.name} age={user.age} />;
}

export default App;

The parent passes the user's name and age to the child component. The child displays the received data without needing to store duplicate state.

9. Updating Parent State from a Child Component

A child component cannot directly modify the parent's state. However, the parent can pass a callback function to the child. When the child calls this function, the parent can update its own state.

Example:

import { useState } from "react";

function Child({ onUpdate }) {
  return (
    <button onClick={onUpdate}>
      Update Parent Message
    </button>
  );
}

function App() {
  const [message, setMessage] = useState("Original Message");

  function updateMessage() {
    setMessage("Updated by Child");
  }

  return (
    <div>
      <h2>{message}</h2>
      <Child onUpdate={updateMessage} />
    </div>
  );
}

export default App;

Explanation:

  1. The parent creates the message state.
  2. The parent defines the updateMessage() function.
  3. The function is passed to the child through the onUpdate prop.
  4. The child calls the function when the button is clicked.
  5. The parent updates its state, and React displays the new message.

10. Sharing State Between Sibling Components

Sibling components are components rendered by the same parent. Since one sibling cannot directly access another sibling's local state, shared state should usually be placed in their closest common parent.

Example:

import { useState } from "react";

function InputComponent({ value, onValueChange }) {
  return (
    <input
      value={value}
      onChange={event => onValueChange(event.target.value)}
      placeholder="Enter your name"
    />
  );
}

function DisplayComponent({ value }) {
  return <h2>Your Name: {value}</h2>;
}

function App() {
  const [name, setName] = useState("");

  return (
    <div>
      <h2>Sibling Components Example</h2>
      <InputComponent value={name} onValueChange={setName} />
      <DisplayComponent value={name} />
    </div>
  );
}

export default App;

How it works:

  • The App component stores the name in state.
  • InputComponent receives the current name and a callback function.
  • When the user types, InputComponent calls the callback with the new input value.
  • The parent updates its state.
  • DisplayComponent receives the new value and displays it immediately.

This is a common pattern for keeping form inputs and displayed information synchronized.

11. Controlled Components

A controlled component is a component whose important input value or behavior is controlled by props supplied by its parent. The parent manages the value, and the child requests changes through callbacks.

Example:

function ControlledInput({ value, onChange }) {
  return (
    <input
      value={value}
      onChange={onChange}
    />
  );
}

In this example, the input value comes from the parent through the value prop. The child does not maintain a separate state for the input value.

12. Uncontrolled Components

An uncontrolled component manages its own important state internally instead of receiving that state value from its parent. This can make the component easier to use independently, but it is less convenient when multiple components must coordinate the same information.

Example:

import { useState } from "react";

function UncontrolledCounter() {
  const [count, setCount] = useState(0);

  return (
    <div>
      <p>Count: {count}</p>
      <button onClick={() => setCount(count + 1)}>
        Increase
      </button>
    </div>
  );
}

Here, the counter manages its own state. Its parent does not directly control the counter value through props.

13. Controlled vs. Uncontrolled Components

Feature Controlled Component Uncontrolled Component
State management Important state is controlled through props. Important state is managed internally.
Parent control Parent can determine the displayed value. Parent has less direct control over internal state.
Coordination Useful for synchronizing multiple components. Useful for independent component behavior.
Configuration Often requires value and callback props. Often requires less parent configuration.
Example Input controlled by parent state. Independent counter with local state.

These terms describe common component design patterns. A component can use both props and its own local state for different pieces of information.

14. Sharing State Through a Common Parent

When two or more components need the same information, identify their closest common parent and move the shared state into that component.

Example: Shared Counter

import { useState } from "react";

function CounterDisplay({ count }) {
  return <h2>Shared Count: {count}</h2>;
}

function CounterButtons({ onIncrease, onDecrease }) {
  return (
    <div>
      <button onClick={onIncrease}>Increase</button>
      <button onClick={onDecrease}>Decrease</button>
    </div>
  );
}

function App() {
  const [count, setCount] = useState(0);

  return (
    <div>
      <CounterDisplay count={count} />
      <CounterButtons
        onIncrease={() => setCount(previous => previous + 1)}
        onDecrease={() => setCount(previous => previous - 1)}
      />
    </div>
  );
}

export default App;

The CounterDisplay component shows the shared count, while CounterButtons provides the controls. Both components work with the same state managed by App.

15. Single Source of Truth

A single source of truth means that each unique piece of shared state has one component responsible for managing it. Other components access that information through props, context, or an appropriate state management solution.

For example, if a shopping cart's item count is needed in the header and checkout page, it is generally better to derive both displays from the same cart state rather than maintaining separate, independently updated counts.

Benefits:

  • Reduces duplicated state.
  • Keeps related components synchronized.
  • Makes updates easier to understand.
  • Reduces inconsistencies between different parts of the interface.
  • Makes component behavior easier to test and maintain.

16. Sharing State Using Props and Callback Functions

Props and callback functions work together to create a one-way data flow. The parent passes state values down to children, and children notify the parent about user actions by calling callbacks.

Example:

import { useState } from "react";

function Child({ count, onIncrease }) {
  return (
    <div>
      <p>Count from Parent: {count}</p>
      <button onClick={onIncrease}>Increase Count</button>
    </div>
  );
}

function App() {
  const [count, setCount] = useState(0);

  return (
    <Child
      count={count}
      onIncrease={() => setCount(previous => previous + 1)}
    />
  );
}

export default App;

The child receives the count as a prop and invokes the callback to request an update. The parent remains responsible for the state.

17. Sharing State Between Distant Components Using Context

When many components need the same information and those components are deeply nested in the component tree, passing props through every intermediate component can become inconvenient. This is often called prop drilling.

React Context provides a way for a parent component to make information available to descendant components without passing the data explicitly through every intermediate component.

Example:

import { createContext, useContext, useState } from "react";

const ThemeContext = createContext();

function ThemeDisplay() {
  const theme = useContext(ThemeContext);

  return <h2>Current Theme: {theme}</h2>;
}

function App() {
  const [theme, setTheme] = useState("Light");

  return (
    <ThemeContext.Provider value={theme}>
      <ThemeDisplay />
      <button
        onClick={() =>
          setTheme(previous =>
            previous === "Light" ? "Dark" : "Light"
          )
        }
      >
        Toggle Theme
      </button>
    </ThemeContext.Provider>
  );
}

export default App;

Explanation:

  • createContext() creates a context for sharing information.
  • The provider makes the current theme available to its descendants.
  • useContext() reads the nearest provider's value.
  • The button updates the theme state in App.
  • React updates the components that consume the changed context value.

Important: Context is useful when many components need the same information across a component tree. For closely related components, lifting state up and passing props is often simpler.

18. Common Mistakes When Sharing State

  • Duplicating shared state: Keeping separate copies of the same information can cause components to become inconsistent.
  • Keeping state too low in the tree: Sibling components cannot directly share each other's local state.
  • Trying to modify parent state directly: Children should call a callback supplied by the parent instead.
  • Forgetting to pass props: A child cannot access a parent's local variables unless the parent provides the required values or uses an appropriate sharing mechanism.
  • Using unnecessary global state: Not every state value needs Context or a global state management library.
  • Passing the wrong callback: Ensure the event handler is invoked at the intended time, such as through onClick.
  • Creating redundant state: If a value can be calculated from existing props or state, consider deriving it instead of storing a separate copy.
  • Ignoring controlled input requirements: If an input receives a value prop, provide an appropriate change handler so the value can be updated.

19. Practical Project: Shared Search Application

Objective: Build a React application where a search input and a results component share state. When the user types in the input, the results list updates automatically.

Complete Code:

import { useState } from "react";

const products = [
  "Laptop",
  "Mobile Phone",
  "Keyboard",
  "Mouse",
  "Monitor",
  "Headphones"
];

function SearchInput({ search, onSearchChange }) {
  return (
    <input
      type="text"
      value={search}
      onChange={event => onSearchChange(event.target.value)}
      placeholder="Search products"
    />
  );
}

function ProductResults({ search }) {
  const filteredProducts = products.filter(product =>
    product.toLowerCase().includes(search.toLowerCase())
  );

  return (
    <div>
      <h3>Search Results</h3>
      {filteredProducts.length > 0 ? (
        <ul>
          {filteredProducts.map(product => (
            <li key={product}>{product}</li>
          ))}
        </ul>
      ) : (
        <p>No products found.</p>
      )}
    </div>
  );
}

function App() {
  const [search, setSearch] = useState("");

  return (
    <div>
      <h2>Product Search</h2>
      <SearchInput
        search={search}
        onSearchChange={setSearch}
      />
      <ProductResults search={search} />
    </div>
  );
}

export default App;

Project Explanation:

  1. The App component stores the search text in state.
  2. SearchInput receives the search value and callback through props.
  3. When the user types, SearchInput calls the callback with the new text.
  4. The App component updates the shared state.
  5. ProductResults receives the updated search text.
  6. The results component filters the product list and displays matching products.

This project demonstrates how lifting state up keeps two sibling components synchronized without maintaining duplicate search values.

20. Best Practices for Sharing State Between Components

  • Identify which components need access to the same information.
  • Move shared state to the closest common parent.
  • Pass state values through props when the component relationship is straightforward.
  • Pass callback functions to children that need to request state updates.
  • Keep each unique piece of state in one authoritative location.
  • Use controlled components when the parent must coordinate input values.
  • Use Context when data must be available to many descendants across a component tree.
  • Derive values from existing state instead of storing redundant copies.
  • Use functional state updates when the next value depends on the previous value.
  • Keep components reusable by clearly defining their props.

21. Interview Questions and Answers

Q1. What is sharing state between components in React?

Answer: It is the process of making the same state information available to multiple components so they can display consistent data and coordinate their behavior.

Q2. What is lifting state up?

Answer: Lifting state up means moving state from child components to their closest common parent and passing the state down through props.

Q3. Why is lifting state up useful?

Answer: It allows sibling components to use the same source of truth, stay synchronized, and avoid maintaining duplicate copies of shared information.

Q4. Can a child component directly update its parent's state?

Answer: No. A child can call a callback function passed by the parent. The callback can then update the parent's state.

Q5. What are props in React?

Answer: Props are values passed from a parent component to a child component. They can contain data, callback functions, and other values needed by the child.

Q6. What is a controlled component?

Answer: A controlled component has important values or behavior managed by its parent through props.

Q7. What is an uncontrolled component?

Answer: An uncontrolled component manages important state internally instead of receiving that state value from its parent.

Q8. What is the single source of truth?

Answer: It means each unique piece of shared state has one authoritative component or state management location responsible for managing it.

Q9. What is prop drilling?

Answer: Prop drilling is the process of passing props through multiple intermediate components that may not use those props themselves, just to reach a deeply nested component.

Q10. How does Context help share state?

Answer: Context makes a value available to descendant components without requiring every intermediate component to pass that value through props.

Q11. Should every state variable be moved to the parent?

Answer: No. State should be lifted only when multiple components need to coordinate or access it. Independent state can remain local to the component that uses it.

Q12. How can two sibling components stay synchronized?

Answer: Store their shared state in their closest common parent and pass the state value and update callbacks to the sibling components through props.

22. Practice Exercises

  1. Create two components that display the same message from a parent state.
  2. Create a counter with separate display and control components.
  3. Build two synchronized input fields that share one text value.
  4. Create a search input and a product results component.
  5. Build a parent component that updates its state when a child button is clicked.
  6. Create an accordion where opening one panel closes another.
  7. Build a theme switcher using React Context.
  8. Create a shopping cart where the header and cart component share the item count.

23. Quick Revision Checklist

  • Understand React state and props.
  • Understand parent-child and sibling component relationships.
  • Learn the concept of lifting state up.
  • Pass shared state from parent to child through props.
  • Pass callback functions to request parent state updates.
  • Understand controlled and uncontrolled components.
  • Maintain a single source of truth for shared information.
  • Understand prop drilling and the purpose of Context.
  • Avoid duplicate state when a value can be derived.
  • Practice building synchronized components.

24. Conclusion

Sharing state between components is an essential concept in React JS. It helps different parts of an application work with the same information and stay synchronized when data changes.

By lifting state up, passing props, using callback functions, and applying React Context when appropriate, developers can create maintainable and reusable applications. These techniques are useful for forms, search interfaces, dashboards, shopping carts, tabs, accordions, and many other interactive features.


25. React JS Training and Course Demo

Learn more about React JS, component communication, state management, and practical application development through JustAcademy.

Course Link: JustAcademy React JS Training

Demo Registration: Register for React JS Course Demo

Previous Next
whatsapp