1

So, when using Context API and useReducer hook, initial state and dispatch function are defined, a Context is created and then a value is returned.

return (
<Context.Provider value={state, dispatch}>
{props.children}
</Context.Provider>
);

Then at some place it's used like this:

dispatch({ type: SET_ERROR, error: errorMessage });

That's a lot of writing each time when dispatch is called at different places (at least to me). I came up with a system where I define a function in the Context file like this:

const setError = (errorMessage) => {
dispatch({ type: SET_ERROR, error: errorMessage });
};

...and then I return setError (and other functions that I create) through the value instead of dispatch and call it where necessary like this:

setError(errorMessage);

It works the same. I perceive it as destructuring dispatch function and simplifying return value for later calls. My question is if this is a good practice? Does it influence performance, re-renders etc?

Ante
  • 101
  • 10
  • 1
    Generally speaking: yes, this is fine. For further reading, look up “action creators”, keeping in mind that React’s useReducer hook is basically a mini version of Redux. – Linda Paiste Feb 23 '22 at 16:53
  • You can use `useCallback` and/or `useMemo` to reduce re-rendering. But you are already passing down the entire `state` object so there is going to be a lot of inevitable re-rendering whenever the `state` changes. – Linda Paiste Feb 23 '22 at 16:56
  • Linda, I'll have a look at action creators. Thanks for the suggestion. – Ante Feb 24 '22 at 05:50
  • I'm actually not passing the entire state. I simplified my example here. I destructure the state too in the Context file, and return individual state values like error, loading, images etc. – Ante Feb 24 '22 at 05:53

0 Answers0