I've looked around on the internet for the solution to this but I still haven't found one that works. I've tried the following state management tools:
- useContext
- Redux
- Zustand
- Recoil
I want my NextJS site to update a value on each page when I click a simple button. Right now I'm using Recoil as I've found it one of the easiest state management tool so far.
This is my _app.js
function MyApp({ Component, pageProps }) {
return (
<RecoilRoot>
< Component {...pageProps} />
</RecoilRoot>
)
}
This is index.js:
export default function Home() {
const [city, setCity] = useRecoilState(cityState)
return (
<>
<h1>{city}</h1>
<button onClick={() => setCity("paris")}>click</button>
</>
);
}
This is page 2
export default function SecondPage() {
const [city, setCity] = useRecoilState(cityState)
return (
<>
<h1>{city}</h1>
</>
);
}
./state/state.js
export const cityState = atom({
key: "cityState",
default: "moscow"
})
When I click the change button on index.js, I simply want it to change for SecondPage and all pages where I reference the state stored in state.js. Right now it changes on index.js but SecondPage stays as "moscow". I want it to update when the button on index is clicked.