Ask Your Question
3

How can dispatch be made to change when using useContext and useReducer in Typescript?

asked 2023-03-31 11:00:00 +0000

pufferfish gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
3

answered 2022-02-20 17:00:00 +0000

bukephalos gravatar image

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.

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2023-03-31 11:00:00 +0000

Seen: 8 times

Last updated: Feb 20 '22