React- Communication between two sibling Components using react Hooks.

Abhishek Bhardwaj
2 min readFeb 6, 2021

In this article, I will show you how you can communicate between two siblings components using react hooks.

2. Sibling communication Diagram

Here as shown in image 2 we will pass our message from child1 to the parent then update the message in child2.
So let’s start:-

Suppose we have a parent component called app.js which has two child components name Child1 and child2.
Our parent app.js code looks like.

import logo from ‘./logo.svg’;import ‘./App.css’;import Child2 from ‘./Child2’;import Child1 from ‘./Child1’;import { useState } from ‘react’;function App() {const [selectedMessage,setMessage]=useState(‘empty’);return (<div className=”app”><Child2 selectedMessage={selectedMessage}/><Child1 setMessage={setMessage}/></div>);}export default App;

Here we create the initial state and set the message empty:-
In the Child1 component, we are setting the message. Our Child1 component looks like.

import React from 'react';export default function Child1({setMessage}) {const onButtonClick=(changeValue)=>{setMessage(changeValue)}return (<div><button onClick={()=>onButtonClick('Message from child 1')}>Child1</button></div>)}

Here on Button click, we are changing the value of our message from empty to “Message from child 1”.

In the Child2 we will show the changed message like below:-

import React,{useState} from ‘react’;import { motion } from “framer-motion”export default function Child2({selectedMessage}) {return (<div><p>{selectedMessage}</p></div>)}

Hope I have cleared your doubt about sibling communication in react.

You can download the full code from here.

Happy Coding :)

--

--

Abhishek Bhardwaj

Coding for the last 6 years. Love mobile development, JavaScript, Java, Reactjs, React Native. Not a coffee lover.