DEV Community

Cover image for React createContext with useReducer TypeScipt

Posted on

React createContext with useReducer TypeScipt

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

export const useStateValue = () => useContext(AppContext);

Enter fullscreen mode Exit fullscreen mode

import the context API and wrapping the child components.


export const actionTypes = {

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 {
        count: state.count + action.count,
      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.


      <App />
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();

  const incrementHandler = () => {
      Type: actionTypes.INCREMENT,
      count: 1,

  return (
    <div className="App">
      <button onClick={incrementHandler}>Add +</button>

export default App;

Enter fullscreen mode Exit fullscreen mode


git repo:


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.

Top comments (1)

andrewbaisden profile image
Andrew Baisden

Cool and easy to read tutorial thanks for sharing.