KylianMbappe
KylianMbappe

Reputation: 2427

State Management in NextJS

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:

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.

Upvotes: 3

Views: 5115

Answers (1)

&#214;mer Ayhan
&#214;mer Ayhan

Reputation: 83

I don't know how your code structure is but I think your easiest option is React Context API. Let's give you an example for a better explanation;

Your Context script:

 import React, { createContext, useState } from "react";

export const GlobalContext = createContext(); // you can set a default value inside createContext if you want


export default function ContextProvider({ children }) {
  const [city, setCity] = useState("moscow")

  return (
    <GlobalContext.Provider
      value={[city, setCity]}>
      {children}
    </GlobalContext.Provider>
  );
}

Your _app.js file:

import ContextProvider from "your_directory"

function MyApp({ Component, pageProps }) {
  return (
    <ContextProvider>
      < Component {...pageProps} />
    </ContextProvider>
  )
}

index.js file:

    import ContextProvider, {GlobalContext} from 'your directory'

export default function Home() {
  const [city, setCity] = useContext(GlobalContext)
  return (
    <>
      <h1>{city}</h1>
      <button onClick={() => setCity("paris")}>click</button>
    </>
   );
}

Your script for Page 2:

import ContextProvider, {GlobalContext} from 'your directory'

export default function SecondPage() {
  const [city] = useContext(GlobalContext)

  return (
    <>
      <h1>{city}</h1>
    </>
   );
}

Upvotes: 3

Related Questions