1 | initial version |
One method is to use React Context. Context provides a way to pass data through the component tree without having to pass props down manually at every level.
To make a local atom accessible throughout the entire child component hierarchy using React Context, follow these steps:
Example code:
import { createContext, useState, useContext } from "react";
const LocalAtomContext = createContext();
function App() {
const [localAtom, setLocalAtom] = useState("value");
return (
<LocalAtomContext.Provider value={localAtom}>
<Child1 />
</LocalAtomContext.Provider>
);
}
function Child1() {
const localAtom = useContext(LocalAtomContext);
return (
<div>
<h1>Child 1</h1>
<p>Local atom value: {localAtom}</p>
<Child2 />
</div>
);
}
function Child2() {
const localAtom = useContext(LocalAtomContext);
return (
<div>
<h2>Child 2</h2>
<p>Local atom value: {localAtom}</p>
</div>
);
}
In this example, the LocalAtomContext is created using createContext(). The App component then wraps the Child1 component in a LocalAtomContext.Provider component, which sets the value of the context to the current value of localAtom using useState().
The Child1 and Child2 components then access the value of the local atom by using useContext(LocalAtomContext) and can use that value as needed.