I've scoured the depths of the internet in search of a solution for this issue, but unfortunately I have yet to come across one that effectively resolves it. I've experimented with various state management tools including:
- useContext
- Redux
- Zustand
- Recoil
My objective is to have my NextJS website update a value on each page whenever a simple button is clicked. Currently, I am utilizing Recoil as it has proven to be one of the most user-friendly state management tools thus far.
This is how my _app.js
looks like:
function MyApp({ Component, pageProps }) {
return (
<RecoilRoot>
<Component {...pageProps} />
</RecoilRoot>
)
}
Here's the code for index.js
:
export default function Home() {
const [city, setCity] = useRecoilState(cityState)
return (
<>
<h1>{city}</h1>
<button onClick={() => setCity("paris")}>click</button>
</>
);
}
Now, let's move on to Page 2:
export default function SecondPage() {
const [city, setCity] = useRecoilState(cityState)
return (
<>
<h1>{city}</h1>
</>
);
}
This is where I declare my state in ./state/state.js
:
export const cityState = atom({
key: "cityState",
default: "moscow"
})
Upon clicking the change button on index.js
, my intention is for this change to reflect not only on that page but also on SecondPage
and any other pages where the state from state.js
is referenced. As it currently stands, the change occurs on index.js
only while SecondPage
retains its original value of "moscow". My goal is for all connected pages to update when the button on index is clicked.