Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

To change the dispatch function when using useContext and useReducer in Typescript, you can create a separate context that contains a different dispatch function.

First, create a new context file, for example, "MyDispatchContext.tsx", and define the dispatch function in it.

import React from "react";

type Dispatch = (action: Action) => void;
type Action = { type: string; payload?: any };

export const MyDispatchContext = React.createContext<Dispatch>(() => {});

export const myDispatchFunction = (action: Action) => {
  // your dispatch function logic here
};

Next, wrap your application with this new context, and pass the dispatch function as a prop to the context provider.

import { MyDispatchContext, myDispatchFunction } from "./MyDispatchContext";

function App() {
  return (
    <MyDispatchContext.Provider value={myDispatchFunction}>
      <MyComponent />
    </MyDispatchContext.Provider>
  );
}

Finally, in the component where you want to use the new dispatch function, replace the useContext hook with the new context.

import { MyDispatchContext } from "./MyDispatchContext";

function MyComponent() {
  const dispatch = useContext(MyDispatchContext);

  const handleButtonClick = () => {
    dispatch({ type: "MY_ACTION" });
  };

  return <button onClick={handleButtonClick}>Click me</button>;
}

Now, when the button in MyComponent is clicked, the dispatch function called will be the one provided by the MyDispatchContext, which can be a different dispatch function than the one used in the rest of the application.