Skip to content Skip to sidebar Skip to footer

Why Is Usereducer's Dispatch Causing Re-renders?

Suppose I implement a simple global loading state like this: // hooks/useLoading.js import React, { createContext, useContext, useReducer } from 'react'; const Context = createCon

Solution 1:

The first issue is that you should never trigger any React state updates while rendering, including useReducers's dispatch() and useState's setters.

The second issue is that yes, dispatching while always cause React to queue a state update and try calling the reducer, and if the reducer returns a new value, React will continue re-rendering. Doesn't matter what component you've dispatched from - causing state updates and re-rendering is the point of useReducer in the first place.

The "stable identity" means that the dispatch variable will point to the same function reference across renders.

Solution 2:

Besides the fact that you're setting state while rendering as has been pointed out, I think I can shed some light about how to take advantage dispatch's stable identity to avoid unnecessary re-renders like you are expecting.

Your Provider value is an object (value={{ isLoading, dispatch}}). This means the identity of the value itself will change when the context's state changes (for example, when isLoading changes). So even if you have a component where you only consume dispatch like so:

const { dispatch } = useLoading()

The component will re-render when isLoading changes.

If you're at the point where you feel re-rendering is getting out of hand, the way to take advantage of dispatch stable identity is to create two Providers, one for the state (isLoading in this case) and one for dispatch, if you do this, a component that only needs dispatch like so:

const dispatch = useLoadingDispatch()

Will not re-render when isLoading changes.

Note that this can be an overoptimization and in simple scenarios might not be worth it.

This is an excellent set of articles for further reading on the subject: https://kentcdodds.com/blog/how-to-optimize-your-context-valuehttps://kentcdodds.com/blog/how-to-use-react-context-effectively

Post a Comment for "Why Is Usereducer's Dispatch Causing Re-renders?"