I am working on something where I need to maintain the application level state i.e global state, I am using react hooks for that useContext
and useReducer
.
So what I am doing is on button click I am setting up my context and then using it thought my application by registering the provider in my App.js
.
I know why I am using my data, because I am setting the initial state to null first, that's why when I refresh the page it sets to null again, but my requirement is not that after button click I want to store that data as a global state so that I can use it further
But this should not be the case I want to make my data global and on refresh it should not lose
My code
My context file
import React, { useReducer, createContext } from "react";
const initialstate = {
someData: null
};
const MyContext = createContext({
someData: null,
click_btn: d => {}
});
const MyReducer = (state, action) => {
switch (action.type) {
case "BTNCLICKED":
return {
...state,
someData: action.payload
};
default:
return state;
}
};
const MyProvider = props => {
const [state, dispatch] = useReducer(MyReducer, initialstate);
const click_btn = d => {
dispatch({
type: "BTNCLICKED",
payload: d
});
};
return (
<MyContext.Provider
value={{ someData: state.someData, click_btn }}
{...props}
/>
);
};
export { MyContext, MyProvider };
My home code where I am setting the context
import React, { useContext, useState } from "react";
import history from "../History/history";
import { MyContext } from "../context/testContext";
function Test() {
const context = useContext(MyContext);
const [data, setdata] = useState(null);
const clickEvt = () => {
setdata("Setting data");
context.click_btn(data);
};
return (
<div>
<input type="button" onClick={clickEvt} value="Click Me" />
</div>
);
}
export default Test;
And my app.js file
import React from "react";
import "./styles.css";
import { MyProvider } from "./context/testContext";
import { Router } from "react-router-dom";
import history from "./History/history";
import Routes from "./myRoutes";
export default () => {
return (
<MyProvider>
<Router history={history}>
<div className="App wrapper">
<Routes />
</div>
</Router>
</MyProvider>
);
};
Please do check working code My codesand box link
Please do check the react developer tools