Skip to main content

Command Palette

Search for a command to run...

How to Pass Data Between Components in React

Published
•2 min read•View as Markdown
How to Pass Data Between Components in React

From Parent -> Child

Data can be passed from a parent component to a child component using props, allowing the child to receive and utilise the data effectively.

// Parent Component
  fuction Parent(){
   const parentData = 'This data belongs to the parent';

    return <Child data={parentData} /> // passing parentData as a prop to the child
  }

// Child Component
  fuction Child({ data }){
    // child is receiving parent data and utilising it
    return <h1>{data}</h1>
  }

From Child -> Parent

The parent component passes a callback function as a prop to the child component, which then calls this callback function and passes the data to it.

// Parent Component
  fuction Parent(){
    const callbackToChild = (dataFromChild)=>{
      console.log(dataFromChild)
    }

    return <Child cb={callbackToChild} /> // passing callback to the child
  }

// Child Component
  fuction Child({ cb }){
    const childData = 'This data is from child';
    const handleClick = (event)=>{
        cb(childData); // calling callback
    }
    return <>
    <h1> Child component </h1>
    <button onClick={handleClick}>Submit Data</button>
    <>
  }

Between Siblings

In React, sibling components do not directly communicate with each other. Instead, the communication typically goes through their common parent.

💡
In React, sibling components are those that share the same immediate parent. Components that share a common ancestor but have different parents are not siblings, even if they are related through the component tree.
  1. Step-by-step:

    1. The common parent holds the shared state.

    2. It passes props (state and callbacks) down to the sibling components.

    3. One sibling updates the state, the other receives the updated state via props.

    function Parent() {
      const [message, setMessage] = React.useState(""); // parent hold the shared state

      return (
        <>
          <SiblingOne setMessage={setMessage} /> 
          <SiblingTwo message={message} />
        </>
      );
    }

    function SiblingOne({ setMessage }) {
      // sibling one updates the state
      return <button onClick={() => setMessage("Hello from Sibling One!")}>Send Message</button>;
    }

    function SiblingTwo({ message }) {
      // sibling two receive the updated state
      return <p>Message Received: {message}</p>;
    }
  1. Using Context API ( For deeply nested siblings)

    For deeply nested sibling components, using the common parent approach can lead to excessive prop drilling as the shared state needs to be passed down through multiple layers. To avoid this, we can use the Context API, which allows us to share data between sibling components without prop drilling.