How to Pass State to Child Components in React

Irakli Tchigladze Feb 02, 2024
  1. Purpose of the State Object
  2. Pass Down Data From Parent to Children Components
  3. Pass State to Child Components in React
  4. Context API to Pass State to Child Components
How to Pass State to Child Components in React

Front-end developers often have to set up a state pattern on the client side to maintain the dynamic features of their web application. This is possible without any frameworks, but it takes a lot of effort.

React has an internal state system and removes a lot of headaches associated with state management.

Purpose of the State Object

In React, we use the state to store external data, user inputs, and other values that might change. For example, we can have a text input that updates a specific state value and then reference and display the state value in JSX.

Therefore, the input updates the state, and then we reference the state to display values. Changes to values in the state trigger a re-render.

Pass Down Data From Parent to Children Components

The most common and simplest way to pass state from parent to children is to do it manually using props. From the component at the top of the tree to its direct children, then that child receives it and passes it down via props to its own children, and so on until it reaches the final destination.

Let’s look at an example:

export default function App() {
  return (
    <div className="App">
      <Box number={11} />
      <Box number={15} />
      <Box number={18} />
    </div>
  );
}
function Box(props) {
  return <div>{props.number}</div>;
}

We have passed down the value from parent to child. In this case, we have to pass it down only one level – from parent to its direct child.

If the child component had its own child component, which had children of its own, then it might be time-consuming to pass down data from parent to child.

In some cases, you might pass down data to children components that do not use this data. This is called prop drilling.

If you notice yourself doing it a lot, you should seek alternatives.

Pass State to Child Components in React

Official React documentation recommends that developers store all state data in the parent component; this practice is called a Single Source of Truth. A child component can have an input element, like a text box.

React allows you to pass down the reference to the function that updates the state in the parent component. You can call the reference to this function in the child component to update the state in the parent component based on the value local to this child component.

Most often, React web apps are structured as component trees. There is a parent component with multiple children.

Each of these children can have multiple children of their own, and there can be dozens of levels in a component tree. And the key is component reusability, so one component can have dozens of instances.

In React, state (and other values) is passed down from the parent to the children using the props object. It works similarly to setting an attribute on a normal HTML element.

Instead, setting this custom attribute in JSX makes that value available to the child component.

Let us look at an example of passing down a state variable to a child component:

import "./styles.css";
import { useState } from "react";
export default function App() {
  const [text, setText] = useState("");
  return (
    <div className="App">
      <input type="Text" onChange={(e) => setText(e.target.value)} />
      <Box paragraph={text} />
    </div>
  );
}
function Box(props) {
  return <div>{props.paragraph}</div>;
}

Live Demo

Children’s components can not pass data up to the parent. This pattern is called Unidirectional Data Flow.

State data is stored in the parent and is passed down to the children’s components.

In the example above, we only have one parent and one child. In simple component trees like this one, it makes sense to use props; however, this approach becomes cumbersome when there are too many children components with their own children.

Fortunately, React offers an alternative, which you can use to make values from the parent instantly available in the children’s components without passing them down on every level.

Context API to Pass State to Child Components

Context API in React allows developers to pass state values to child components without using props. The data becomes accessible to all children.

This is much easier than individually passing down a single data piece to many child components.

Imagine we have to pass down these values to many child components. We will need to do something like this:

export default function App() {
  return (
    <>
      <Child darkMode={true} />
      <Child darkMode={true} />
      <Child darkMode={true} />
    </>
  );
}

function Child ({ darkMode }) {
  return (
    <>
      <Text darkMode={theme} />
      <Video darkMode={theme} />
      <Visual darkMode={theme} />
      <Card darkMode={theme} />
    </>
  );
}

In this component, the parent component at the top has three <Child> components, which have child components like <Text>, <Video>, <Visual>, <Card>, and more. We need to pass down this data to these children and any children they might have.

Looking at the code, it becomes obvious that this approach is inefficient.

State values like theme data (dark mode settings) and user data (authentication information) can be necessary to customize the visuals and functionality of the child components. Instead of manually passing it down one by one, React developers can use the Context API to pass state to child components without doing it via props.

Use Context to Pass State to Child Components

React library contains a createContext() method that React developers can use to create context. It is easier if we break down implementing Context API into four easy steps:

  1. Create context using the createContext() method.
  2. Wrap the context provider around the component tree.
  3. Set the value prop on the context provider equal to the value you like to share throughout the component tree.
  4. Access the value in child components by using a useContext() hook.

Let us create an example code and go through each step.

First, we define a functional component, which will be the parent of other components. We use the createContext() method to create context in this parent component, and store reference in the dataContext variable.

import "./styles.css";
import React from "react";
import { useState, useContext } from "react";
const dataContext = React.createContext();

export default function App() {
  const [darkMode, setDarkMode] = useState(true);
  return (
    <dataContext.Provider value={darkMode}>
      <div>
        <Child />
      </div>
    </dataContext.Provider>
  );
}
function Child() {
  return (
    <div>
      <Grandchild />
    </div>
  );
}
function Grandchild() {
  const setting = useContext(dataContext);
  console.log(setting);
  return (
    <div
      style={{
        width: 300,
        height: 300,
        backgroundColor: setting ? "black" : "white",
        color: setting ? "white" : "black"
      }}
    >
      Hello, World
    </div>
  );
}

In the parent App component, we have a child component that has a child component of its own.

We wrap the entire component tree in the parent component with a context provider and set the darkMode attribute on the context provider. This value becomes available to all children.

We must use the useContext() hook in the child components. This is needed to use the value set to the Context provider in the parent component.

In this case, we use the darkMode value to set conditional styles in the child component. You can try changing this value in the parent component (change the initial value passed to the useState() hook).

Also, go to the console and see the confirmation that the darkMode state was successfully passed down from the parent to the child via Context API.

Irakli Tchigladze avatar Irakli Tchigladze avatar

Irakli is a writer who loves computers and helping people solve their technical problems. He lives in Georgia and enjoys spending time with animals.

LinkedIn

Related Article - React State