Created
May 8, 2024 08:27
-
-
Save mishaj-7/683cc02666dbc612b231864d320424bc to your computer and use it in GitHub Desktop.
useReaducer hook using context
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// THIS IS CONTEXT CRATEION USING useReducer HOOK | |
import { createContext, useReducer } from "react"; | |
export const AgeContext = createContext(); | |
const ageReducer = (state, action) => { | |
switch (action.type) { | |
case "ADD_ONE": | |
return state + 1; | |
case "ADD_FIVE": | |
return state + 5; | |
case "ADD_NUM": | |
return state + action.num; | |
default: | |
return state; | |
} | |
}; | |
//dispatch({ type: "ADD_ONE" }); | |
const AgeContextProvider = (props) => { | |
const [age, dispatch] = useReducer(ageReducer, 20); | |
return ( | |
<AgeContext.Provider value={{ age, dispatch }}> | |
{props.children} | |
</AgeContext.Provider> | |
); | |
}; | |
export default AgeContextProvider; | |
//USING OF CONTEXT OF useReducer HOOK // | |
import { useContext } from "react"; | |
import { AgeContext } from "../Context/SampleContext"; | |
const Sample = () => { | |
const { age, dispatch } = useContext(AgeContext); | |
return ( | |
<div style={{ padding: "10px", margin: "75px" }}> | |
Age:{age} | |
<button | |
style={{ padding: "10px", margin: "25px" }} | |
onClick={() => dispatch({ type: "ADD_ONE" })} | |
> | |
ADD ONE | |
</button> | |
<button | |
style={{ padding: "10px", margin: "25px" }} | |
onClick={() => dispatch({ type: "ADD_NUM", num: 10 })} | |
> | |
ADD NUM | |
</button> | |
</div> | |
); | |
}; | |
export default Sample; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment