in this tutorial, I'll be exploring the React Context APIs for state management with useReudcer
hook. we don't need to install any third-party library or some stuff, this is all the core feature. so let's right get into that!
First create a folder under src/
named state
like so src/state
. and then we need two files StateProvider.tsx
, and reducer.ts
.
now, write the below code inside StateProvider.tsx
file
import React, { createContext, useContext, useReducer } from "react";
import { reducer, initialState, State } from "./reducer";
const AppContext = createContext<any>(null);
interface Props {
children: JSX.Element | JSX.Element[];
}
export const StateProvider: React.FC<Props> = ({ children }) => (
<AppContext.Provider value={useReducer(reducer, initialState)}>
{children}
</AppContext.Provider>
);
export const useStateValue = () => useContext(AppContext);
import the context API and wrapping the child components.
Reudcer.ts
export const actionTypes = {
INCREMENT: "INCREMENT",
};
export interface State {
count: number;
}
export const initialState: State = {
count: 0,
};
export const reducer = (state = initialState, action: any) => {
switch (action.Type) {
case actionTypes.INCREMENT:
return {
...state,
count: state.count + action.count,
};
default:
return state;
}
};
creating reducer function and conditionally checking the Type.
Wrapping out
We need to wrap out the <App />
component so that we can access the state globally.
/src/index.tsx
<React.StrictMode>
<StateProvider>
<App />
</StateProvider>
</React.StrictMode>,
Access and Dispatch
now you can access the state and dispatch it easily using the useStateValue
function as a hook
import React from "react";
import { useStateValue } from "./state/StateProvider";
import { actionTypes } from "./state/reducer";
import "./App.css";
function App() {
const [state, dispatch] = useStateValue();
console.log(state);
const incrementHandler = () => {
dispatch({
Type: actionTypes.INCREMENT,
count: 1,
});
};
return (
<div className="App">
<button onClick={incrementHandler}>Add +</button>
<h2>{state.count}</h2>
</div>
);
}
export default App;
`
git repo: https://github.com/lifeeric/react-context-with-useReducer/tree/master
Thank
If this post helps you, make sure to share with your friends, family, colleague, and co-worker.
I'm currently Looking for Jobs, If you have an opportunity for me, please consider me.
https://ericgit.me
Top comments (1)
Cool and easy to read tutorial thanks for sharing.