React Pass State Across Parallel Components

- 1 answer


I have two Components of the same level (no owner-ownee relation). Suppose by clicking "C" in Component A, I set the temperature unit to "C", and clicking "F", I set the unit to "F". In Component B, I need to display the temperature, so I need to get the unit. But that information is in A. I wonder how I can access the state in Component A?

Follow up:

In another Component C, which is also parallel to A and B, I have a link to another page:

<div className="bottom_link">
     <Link to={'weather-stations/eaB1rJytnpS5mZ2m'}>view detail</Link>

I also need to pass the unit info to that page. I wonder what is the recommended way to do this? Thanks.




The best way to do this now is with the useContext hook. Create a new file that can be called TemperatureContext.js. In there you will need the following:

import {createContext} from 'react'

export const Temperature = createContext(null);
//you can replace null with an initial condition

Then, in your app.js file import the file you made and create a useState value. Then, wrap both Component A and Component B in a provider tag:

import React, {useState} from 'react'
import{Temperature} from '.TemperatureContext.js'
function App(){
const [temperature, setTemperature] = useState();

<Temperature.Provider value={{temperature, setTemperature}}>

Then, in each of your components, you can import the temperature state by

import React, {useContext} from 'react';
import{Temperature} from '.TemperatureContext.js';

function ComponentA(){
const [temperature, setTemperature] = useContext(Temperature);
const tempChange(entry)=>{


Now, by using the tempChange function in ComponentA, it will alter the state in everything that is wrapped within the Provider tags. Thankfully, react has advanced a long way since this question was posted.