DEV Community

Cover image for React createContext with useReducer TypeScipt
HasOne
HasOne

Posted on

7 2

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

Sentry blog image

How I fixed 20 seconds of lag for every user in just 20 minutes.

Our AI agent was running 10-20 seconds slower than it should, impacting both our own developers and our early adopters. See how I used Sentry Profiling to fix it in record time.

Read more

Top comments (1)

Collapse
 
andrewbaisden profile image
Andrew Baisden

Cool and easy to read tutorial thanks for sharing.

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay