loading...
Cover image for React Context's dispatch...is it part of the dark arts?

React Context's dispatch...is it part of the dark arts?

austinblade profile image Austin Blade ・2 min read

Recently I was tasked to put together some documents for my company explaining our front-end architecture. We use React Context for state management, and I was writing a bit about how we layout our version of the context pattern. Breaking it down..I began to realize that I didn't exactly know what the heck a dispatch does. All I knew was that the dispatch is something useReducer poops out that magically tells my reducer to update state. Could it be part of the dark arts?? While plausible, the answer is no.

Let's make our own VERY SIMPLIFIED version of a dispatch so that we can understand what's going on and convince our grandmothers that we are not using witchcraft.

At its core, a dispatch is just a function.

const dispatch = () => {
};
Enter fullscreen mode Exit fullscreen mode

We know that we pass an action into the dispatch, and a rule is that the action must be an object.

const dispatch = (action: {}) => {
};
Enter fullscreen mode Exit fullscreen mode

Within this dispatch, there's a lot going on that the geniuses on the React team have put together. However, we're going to focus on the main abstraction that makes the dispatch make sense. The dispatch actually calls your reducer!

mind blown gif

const dispatch = (action: {}) => {
    state = reducer(state, action);
};
Enter fullscreen mode Exit fullscreen mode

When the reducer is called, the state is set to whatever your reducer pooped out. React sees that the state was updated and re-renders the component. The new state is returned to the component where we called useReducer initially.

Hopefully, that demystifies dispatch for you and saves your grandmother some worry over her precious grandchild.

grandmother gif

Discussion

pic
Editor guide
Collapse
matiasgdev profile image
Matias Gabriel

I love the mention of grandma, very didactic.

Collapse
austinblade profile image
Austin Blade Author

😂😂😂