0

I'm trying to implement the approach from the accepted answer to this question.

I want a minimal global state on my project using Context in React, and I want to be able to update it very infrequently. This is what my code looks like:

layout.tsx

import { MyContext } from "@/context/myContext";
import { useState } from "react";
import Home from "@/pages/home"


export default function RootLayout({ children }) {
  const [value, setValue] = useState("init");
  const valueStore = { value, setValue };
  return (
    <html lang="en">
        <MyContext.Provider value={valueStore}>
          <body>
            <Home/>
          </body>
        </MyContext.Provider>
    </html>
  );
}

myContext.ts

import { Dispatch, SetStateAction, createContext } from 'react';

export const MyContext = createContext({
    value: "",
    setValue: (() => {}) as Dispatch<SetStateAction<string>>
})

home.tsx

import { useContext, useState } from "react";
import { MyContext } from "@/context/myContext";

export default function Home() {
  const { value, setValue } = useContext(MyContext)

  const handleSubmit = (e) => {
    e.preventDefault();
    setValue("new val")
  };

  return (
    <>
        <button onClick={handleSubmit}>
        {value}
    </>
  );
}

Even after I click, the button, the value is always "", it never updates to "init" or "new val". What am I doing wrong?

I'm using Next.js and the built-in router.

LW001
  • 2,452
  • 6
  • 27
  • 36
Miles Acq
  • 71
  • 1
  • 9

1 Answers1

0

I needed to add pages/_app.tsx:

export default function MyApp({ Component, pageProps }: AppProps) {
  const [value, setValue] = useState("");
  const valueStore = { value, setValue };

  return (
    <MyContext.Provider value={valueStore}>
      <Component {...pageProps} />
    </MyContext.Provider>
  );
}

https://nextjs.org/docs/pages/building-your-application/routing/custom-app

LW001
  • 2,452
  • 6
  • 27
  • 36
Miles Acq
  • 71
  • 1
  • 9