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
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
add a comment |
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
add a comment |
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
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
javascript reactjs react-hooks react-context
asked Mar 8 at 2:17
ChillyPenguin672ChillyPenguin672
8917
8917
add a comment |
add a comment |
1 Answer
1
active
oldest
votes
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
Wow this answer is golden, much appreciated!
– ChillyPenguin672
Mar 8 at 5:58
add a comment |
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
);
);
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
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
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
Wow this answer is golden, much appreciated!
– ChillyPenguin672
Mar 8 at 5:58
add a comment |
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
Wow this answer is golden, much appreciated!
– ChillyPenguin672
Mar 8 at 5:58
add a comment |
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
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
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
add a comment |
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
add a comment |
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.
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
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
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
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