I am wondering how to share state between my two routes. Should I lift state up from my AddContact
component to Layout
or App
to share to ContactList
. My Layout
component is just rendering a Header
and Outlet
component.
function App() {
const [contacts, setContacts] = useState([])
return (
<BrowserRouter>
<Routes>
<Route element={<Layout />}>
<Route path='/' element={<ContactList />} />
<Route path='/add' element={<AddContact />} />
</Route>
</Routes>
</BrowserRouter>
);
}
2
Answers
You could lift it to either.
If lifting state to
App
you can pass what you need down as props to each routed component.Example:
The alternative is to locate the state in the
Layout
layout route component and expose via theOutlet
component’s context. The routed components would access the provided context value via theuseOutletContext
hook.It basically comes down to preference, or scope in my opinion, e.g. how much of the sub-ReactTree needs to access the state.
Here is an example using states and not state management systems.
Let’s assume that we’ve got 2 sibling components; page1 and page2. If we need to pass data from the page1 component to the page2 component, we can use hooks in react-router-dom v6.
On the page2 component, you can receive the object like that.