Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React useReducer Hook fires twice / how to pass props to reducer?

FOREWORD / DESCRIPTION

I am trying to use React's new hooks feature for an e-commerce website that I am building, and have been having an issue working a bug out of my shopping cart component.

I think it is relevant to preface the discussion with the fact that I am trying to keep my global state modular by using multiple Context components. I have a separate context component for the types of items that I offer, and a separate context component for the items in a person's shopping cart.

PROBLEM

The issue I am having is that when I dispatch an action to add a component to my cart, the reducer will run twice as if I had added the item to my cart twice. But only when it is initially rendered, or for weird reasons such as the display is set to hidden and then back to block or for a change in the z-index and potentially other similar changes.

I know this is kind of verbose, but it is rather knit picky issue so I have created two codepens that showcase the issue:

full example

minimum example

You will see that I have included a button to toggle the display of the components. This will help showcase the correlation of the css to the issue.

Finally please monitor the console in the code pens, this will show all button clicks and which part of each reducer has been run. The issues are most evident in the full example, but the console statements display the issue is also present in the minimum example.

PROBLEM AREA

I have pinpointed the problem to be related to the fact that I am using the state of a useContext hook to get the items list. A function is called to generate the reducer for my useReducer hook, but only arises when a different hook is used AKA I could use a function that wouldn't be subject to re-eval like hook is and not have the issue, but I also need the info from my previous Context so that workaround doesn't really fix my issue.

Relevant Links

I have determined the issue is NOT an HTML issue so I will not include the links to the HTML fixes I have tried. The issue, while triggered by css, is not rooted in css so I will not include css links either.

useReducer Action dispatched twice

like image 289
Spencer Duball Avatar asked Mar 08 '19 02:03

Spencer Duball


2 Answers

As you indicated, the cause is the same as the related answer of mine that you linked to. You are re-creating your reducer whenever Provider is re-rendered, so in some cases React will execute the reducer in order to determine whether or not it needs to re-render Provider and if it does need to re-render it will detect that the reducer is changed, so React needs to execute the new reducer and use the new state produced by it rather than what was returned by the previous version of the reducer.

When you can't just move the reducer out of your function component due to dependencies on props or context or other state, the solution is to memoize your reducer using useCallback, so that you only create a new reducer when its dependencies change (e.g. productsList in your case).

The other thing to keep in mind is that you shouldn't worry too much about your reducer executing twice for a single dispatch. The assumption React is making is that reducers are generally going to be fast enough (they can't do anything with side effects, make API calls, etc.) that it is worth the risk of needing to re-execute them in certain scenarios in order to try to avoid unnecessary re-renders (which could be much more expensive than the reducer if there is a large element hierarchy underneath the element with the reducer).

Here's a modified version of Provider using useCallback:

const Context = React.createContext();
const Provider = props => {
  const memoizedReducer = React.useCallback(createReducer(productsList), [productsList])
  const [state, dispatch] = React.useReducer(memoizedReducer, []);

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

Here is a modified version of your codepen: https://codepen.io/anon/pen/xBdVMp?editors=0011

Here are a couple answers related to useCallback that might be helpful if you aren't familiar with how to use this hook:

  • Trouble with simple example of React Hooks useCallback
  • React Hooks useCallback causes child to re-render
like image 114
Ryan Cogswell Avatar answered Oct 16 '22 01:10

Ryan Cogswell


Seperate the Reducer from the functional component that helped me solve mine

like image 34
user4920718 Avatar answered Oct 16 '22 03:10

user4920718