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.