DEV Community

loading...
Cover image for React createContext with useReducer TypeScipt

React createContext with useReducer TypeScipt

HasOne
A TECH enthusiast Guy, who is mad to change himself to be able to change the World. and learning how to share happiness and how to enjoy other's success!
・2 min read

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.

Screenshot from 2020-12-25 05-08-30

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);

Enter fullscreen mode Exit fullscreen mode

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;
  }
};

Enter fullscreen mode Exit fullscreen mode

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>,
Enter fullscreen mode Exit fullscreen mode

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;

Enter fullscreen mode Exit fullscreen mode


`

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

Discussion (1)

Collapse
andrewbaisden profile image
Andrew Baisden

Cool and easy to read tutorial thanks for sharing.

Forem Open with the Forem app