I want to use Recoil to share a state between to React Router Routes. My setup looks something like this:
ReactDOM.render(
<React.StrictMode>
<RecoilRoot>
<BrowserRouter>
<Routes>
<Route path="/" element={<App />} />
<Route path="/checkin" element={<Checkin />} />
<Route path="/checkin/confirm" element={<ConfirmCheckin />} />
</Routes>
</BrowserRouter>
</RecoilRoot>
</React.StrictMode>,
document.getElementById("root")
);
My atom setup looks like this:
const checkinItemsState = atom<InventoryItem[]>({
key: "checkinItemsState",
default: [],
});
In both components i use useRecoilState(checkinItemsState)
Now when i open localhost:3000/checkin it shows my state and i can modify it. When i then navigate to localhost:3000/checkin/confirm my state is just an empty array.
What am I missing here? is there something i misunderstand?
So fare I've tried to wrap my Routes with a component like:
const Index: React.FC<{ children: ReactNode }> = ({ children }) => {
useRecoilState(checkinItemsState);
return (
<>
<span>Hello World</span>
{children}
</>
);
};
I guessed maybe it was because the state was nowhere referenced when moving between urls. This does not work.
Any help would be appreciated.