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
What's that red-plus icon near a text?
NMaximize is not converging to a solution
Could an aircraft fly or hover using only jets of compressed air?
How can bays and straits be determined in a procedurally generated map?
What defenses are there against being summoned by the Gate spell?
Do infinite dimensional systems make sense?
Is it inappropriate for a student to attend their mentor's dissertation defense?
Has there ever been an airliner design involving reducing generator load by installing solar panels?
Can I ask the recruiters in my resume to put the reason why I am rejected?
Why does Kotter return in Welcome Back Kotter?
Accidentally leaked the solution to an assignment, what to do now? (I'm the prof)
Why is consensus so controversial in Britain?
Why is Minecraft giving an OpenGL error?
Malcev's paper "On a class of homogeneous spaces" in English
What's the point of deactivating Num Lock on login screens?
Today is the Center
How to format long polynomial?
How much of data wrangling is a data scientist's job?
How to draw a waving flag in TikZ
Why "Having chlorophyll without photosynthesis is actually very dangerous" and "like living with a bomb"?
Convert two switches to a dual stack, and add outlet - possible here?
Is it possible to do 50 km distance without any previous training?
Intersection point of 2 lines defined by 2 points each
I'm flying to France today and my passport expires in less than 2 months
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
.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty height:90px;width:728px;box-sizing:border-box;
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
thank you for your excellent explanation! <3
– manu
2 days ago
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
thank you for your excellent explanation! <3
– manu
2 days ago
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
thank you for your excellent explanation! <3
– manu
2 days ago
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,9081625
5,9081625
Wow this answer is golden, much appreciated!
– ChillyPenguin672
Mar 8 at 5:58
thank you for your excellent explanation! <3
– manu
2 days ago
add a comment |
Wow this answer is golden, much appreciated!
– ChillyPenguin672
Mar 8 at 5:58
thank you for your excellent explanation! <3
– manu
2 days ago
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
thank you for your excellent explanation! <3
– manu
2 days ago
thank you for your excellent explanation! <3
– manu
2 days ago
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