React useReducer Hook fires twice / how to pass props to reducer?useReducer Action dispatched twiceTrouble with simple example of React Hooks useCallbackReact Hooks useCallback causes child to re-renderHow do I pass command line arguments to a Node.js program?React JSX: Access Props in QuotesPass props to parent component in React.jsreact-router - pass props to handler componentWhat is the difference between state and props in React?React js onClick can't pass value to methodHow to pass props to this.props.childrenUpdate React component by dispatching action from non-react componentReact componentDidUpdate not receiving latest propsReact/Redux actions not firing onClick, but exists in component props

putting logo on same line but after title, latex

Is aluminum electrical wire used on aircraft?

Does IPv6 have similar concept of network mask?

Can disgust be a key component of horror?

Mimic lecturing on blackboard, facing audience

Does malloc reserve more space while allocating memory?

How should I respond when I lied about my education and the company finds out through background check?

Is there a RAID 0 Equivalent for RAM?

What features enable the Su-25 Frogfoot to operate with such a wide variety of fuels?

What if a revenant (monster) gains fire resistance?

Terse Method to Swap Lowest for Highest?

Why is it that I can sometimes guess the next note?

Why does AES have exactly 10 rounds for a 128-bit key, 12 for 192 bits and 14 for a 256-bit key size?

Can the US President recognize Israel’s sovereignty over the Golan Heights for the USA or does that need an act of Congress?

Why can Carol Danvers change her suit colours in the first place?

Can a stoichiometric mixture of oxygen and methane exist as a liquid at standard pressure and some (low) temperature?

How do you respond to a colleague from another team when they're wrongly expecting that you'll help them?

Angel of Condemnation - Exile creature with second ability

15% tax on $7.5k earnings. Is that right?

Electoral considerations aside, what are potential benefits, for the US, of policy changes proposed by the tweet recognizing Golan annexation?

What exact color does ozone gas have?

How does the math work for Perception checks?

Quoting Keynes in a lecture

What happens if you are holding an Iron Flask with a demon inside and walk into an Antimagic Field?



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


useReducer Action dispatched twiceTrouble with simple example of React Hooks useCallbackReact Hooks useCallback causes child to re-renderHow do I pass command line arguments to a Node.js program?React JSX: Access Props in QuotesPass props to parent component in React.jsreact-router - pass props to handler componentWhat is the difference between state and props in React?React js onClick can't pass value to methodHow to pass props to this.props.childrenUpdate React component by dispatching action from non-react componentReact componentDidUpdate not receiving latest propsReact/Redux actions not firing onClick, but exists in component props













3















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










share|improve this question


























    3















    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










    share|improve this question
























      3












      3








      3








      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










      share|improve this question














      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







      javascript reactjs react-hooks react-context






      share|improve this question













      share|improve this question











      share|improve this question




      share|improve this question










      asked Mar 8 at 2:17









      ChillyPenguin672ChillyPenguin672

      8917




      8917






















          1 Answer
          1






          active

          oldest

          votes


















          4














          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





          share|improve this answer























          • Wow this answer is golden, much appreciated!

            – ChillyPenguin672
            Mar 8 at 5:58










          Your Answer






          StackExchange.ifUsing("editor", function ()
          StackExchange.using("externalEditor", function ()
          StackExchange.using("snippets", function ()
          StackExchange.snippets.init();
          );
          );
          , "code-snippets");

          StackExchange.ready(function()
          var channelOptions =
          tags: "".split(" "),
          id: "1"
          ;
          initTagRenderer("".split(" "), "".split(" "), channelOptions);

          StackExchange.using("externalEditor", function()
          // Have to fire editor after snippets, if snippets enabled
          if (StackExchange.settings.snippets.snippetsEnabled)
          StackExchange.using("snippets", function()
          createEditor();
          );

          else
          createEditor();

          );

          function createEditor()
          StackExchange.prepareEditor(
          heartbeatType: 'answer',
          autoActivateHeartbeat: false,
          convertImagesToLinks: true,
          noModals: true,
          showLowRepImageUploadWarning: true,
          reputationToPostImages: 10,
          bindNavPrevention: true,
          postfix: "",
          imageUploader:
          brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
          contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
          allowUrls: true
          ,
          onDemand: true,
          discardSelector: ".discard-answer"
          ,immediatelyShowMarkdownHelp:true
          );



          );













          draft saved

          draft discarded


















          StackExchange.ready(
          function ()
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55055793%2freact-usereducer-hook-fires-twice-how-to-pass-props-to-reducer%23new-answer', 'question_page');

          );

          Post as a guest















          Required, but never shown

























          1 Answer
          1






          active

          oldest

          votes








          1 Answer
          1






          active

          oldest

          votes









          active

          oldest

          votes






          active

          oldest

          votes









          4














          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





          share|improve this answer























          • Wow this answer is golden, much appreciated!

            – ChillyPenguin672
            Mar 8 at 5:58















          4














          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





          share|improve this answer























          • Wow this answer is golden, much appreciated!

            – ChillyPenguin672
            Mar 8 at 5:58













          4












          4








          4







          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





          share|improve this answer













          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






          share|improve this answer












          share|improve this answer



          share|improve this answer










          answered Mar 8 at 4:13









          Ryan CogswellRyan Cogswell

          5,4111624




          5,4111624












          • Wow this answer is golden, much appreciated!

            – ChillyPenguin672
            Mar 8 at 5:58

















          • Wow this answer is golden, much appreciated!

            – ChillyPenguin672
            Mar 8 at 5:58
















          Wow this answer is golden, much appreciated!

          – ChillyPenguin672
          Mar 8 at 5:58





          Wow this answer is golden, much appreciated!

          – ChillyPenguin672
          Mar 8 at 5:58



















          draft saved

          draft discarded
















































          Thanks for contributing an answer to Stack Overflow!


          • Please be sure to answer the question. Provide details and share your research!

          But avoid


          • Asking for help, clarification, or responding to other answers.

          • Making statements based on opinion; back them up with references or personal experience.

          To learn more, see our tips on writing great answers.




          draft saved


          draft discarded














          StackExchange.ready(
          function ()
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55055793%2freact-usereducer-hook-fires-twice-how-to-pass-props-to-reducer%23new-answer', 'question_page');

          );

          Post as a guest















          Required, but never shown





















































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown

































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown







          Popular posts from this blog

          Identity Server 4 is not redirecting to Angular app after login2019 Community Moderator ElectionIdentity Server 4 and dockerIdentityserver implicit flow unauthorized_clientIdentityServer Hybrid Flow - Access Token is null after user successful loginIdentity Server to MVC client : Page Redirect After loginLogin with Steam OpenId(oidc-client-js)Identity Server 4+.NET Core 2.0 + IdentityIdentityServer4 post-login redirect not working in Edge browserCall to IdentityServer4 generates System.NullReferenceException: Object reference not set to an instance of an objectIdentityServer4 without HTTPS not workingHow to get Authorization code from identity server without login form

          2005 Ahvaz unrest Contents Background Causes Casualties Aftermath See also References Navigation menue"At Least 10 Are Killed by Bombs in Iran""Iran"Archived"Arab-Iranians in Iran to make April 15 'Day of Fury'"State of Mind, State of Order: Reactions to Ethnic Unrest in the Islamic Republic of Iran.10.1111/j.1754-9469.2008.00028.x"Iran hangs Arab separatists"Iran Overview from ArchivedConstitution of the Islamic Republic of Iran"Tehran puzzled by forged 'riots' letter""Iran and its minorities: Down in the second class""Iran: Handling Of Ahvaz Unrest Could End With Televised Confessions""Bombings Rock Iran Ahead of Election""Five die in Iran ethnic clashes""Iran: Need for restraint as anniversary of unrest in Khuzestan approaches"Archived"Iranian Sunni protesters killed in clashes with security forces"Archived

          Can't initialize raids on a new ASUS Prime B360M-A motherboard2019 Community Moderator ElectionSimilar to RAID config yet more like mirroring solution?Can't get motherboard serial numberWhy does the BIOS entry point start with a WBINVD instruction?UEFI performance Asus Maximus V Extreme