React hooks value is not accessible in event listener functionSet a default parameter value for a JavaScript functionReact Hooks, useReducer not able to get stateReact Hooks - What's happening under the hood?React Hooks: accessing state across functions without changing event handler function referencescomponentWillReceiveProps, componentDidUpdate for React HookCan you early return with React hooks?React hooks function component prevent re-render on state updateReact Hooks, rerender & keeping same state - how it works underhood?Using react hooks inside render prop functionUnsubscribe from event listener react hooks
SOQL Not Recognizing Field?
Is using haveibeenpwned to validate password strength rational?
Why is one of Madera Municipal's runways labelled with only "R" on both sides?
Share calendar details request from manager's manager
How do governments keep track of their issued currency?
Is the term 'open source' a trademark?
Using "subway" as name for London Underground?
How can I get an unreasonable manager to approve time off?
Winning Strategy for the Magician and his Apprentice
Taxi Services at Didcot
Difference between > and >> when used with a named pipe
Pre-1972 sci-fi short story or novel: alien(?) tunnel where people try new moves and get destroyed if they're not the correct ones
PhD - Well known professor or well known school?
Why was the Sega Genesis marketed as a 16-bit console?
1980s live-action movie where individually-coloured nations on clouds fight
How to handle self harm scars on the arm in work environment?
Generate a Graeco-Latin square
System.StringException: Unexpected end of expression
Is open-sourcing the code of a webapp not recommended?
English word for "product of tinkering"
What makes Ada the language of choice for the ISS's safety-critical systems?
Overlapping String-Blocks
Are there any important biographies of nobodies?
A curious prime counting approximation or just data overfitting?
React hooks value is not accessible in event listener function
Set a default parameter value for a JavaScript functionReact Hooks, useReducer not able to get stateReact Hooks - What's happening under the hood?React Hooks: accessing state across functions without changing event handler function referencescomponentWillReceiveProps, componentDidUpdate for React HookCan you early return with React hooks?React hooks function component prevent re-render on state updateReact Hooks, rerender & keeping same state - how it works underhood?Using react hooks inside render prop functionUnsubscribe from event listener react hooks
.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty height:90px;width:728px;box-sizing:border-box;
I decided to use React hooks for my component using windom width and resize event listener. The problem is that I can't access current value that I need. I get nested value that was set while adding event listener.
Passing function to value setter function is not a solution for me because it's forcing render and breaking my other functionalities.
I am attaching minimalistic example to present core problem:
import React, Component, useState, useEffect from 'react';
import render from 'react-dom';
const App = () =>
const [width, setWidth] = useState(0);
const resize = () =>
console.log("width:", width); // it's always 0 even after many updates
setWidth(window.innerWidth);
;
useEffect(() =>
resize();
window.addEventListener("resize", resize);
return () => window.removeEventListener("resize", resize);
, []);
return <div>width</div>;
render(<App />, document.getElementById('root'));
LIVE DEMO IS HERE
Please for help.
javascript reactjs addeventlistener react-hooks
add a comment |
I decided to use React hooks for my component using windom width and resize event listener. The problem is that I can't access current value that I need. I get nested value that was set while adding event listener.
Passing function to value setter function is not a solution for me because it's forcing render and breaking my other functionalities.
I am attaching minimalistic example to present core problem:
import React, Component, useState, useEffect from 'react';
import render from 'react-dom';
const App = () =>
const [width, setWidth] = useState(0);
const resize = () =>
console.log("width:", width); // it's always 0 even after many updates
setWidth(window.innerWidth);
;
useEffect(() =>
resize();
window.addEventListener("resize", resize);
return () => window.removeEventListener("resize", resize);
, []);
return <div>width</div>;
render(<App />, document.getElementById('root'));
LIVE DEMO IS HERE
Please for help.
javascript reactjs addeventlistener react-hooks
add a comment |
I decided to use React hooks for my component using windom width and resize event listener. The problem is that I can't access current value that I need. I get nested value that was set while adding event listener.
Passing function to value setter function is not a solution for me because it's forcing render and breaking my other functionalities.
I am attaching minimalistic example to present core problem:
import React, Component, useState, useEffect from 'react';
import render from 'react-dom';
const App = () =>
const [width, setWidth] = useState(0);
const resize = () =>
console.log("width:", width); // it's always 0 even after many updates
setWidth(window.innerWidth);
;
useEffect(() =>
resize();
window.addEventListener("resize", resize);
return () => window.removeEventListener("resize", resize);
, []);
return <div>width</div>;
render(<App />, document.getElementById('root'));
LIVE DEMO IS HERE
Please for help.
javascript reactjs addeventlistener react-hooks
I decided to use React hooks for my component using windom width and resize event listener. The problem is that I can't access current value that I need. I get nested value that was set while adding event listener.
Passing function to value setter function is not a solution for me because it's forcing render and breaking my other functionalities.
I am attaching minimalistic example to present core problem:
import React, Component, useState, useEffect from 'react';
import render from 'react-dom';
const App = () =>
const [width, setWidth] = useState(0);
const resize = () =>
console.log("width:", width); // it's always 0 even after many updates
setWidth(window.innerWidth);
;
useEffect(() =>
resize();
window.addEventListener("resize", resize);
return () => window.removeEventListener("resize", resize);
, []);
return <div>width</div>;
render(<App />, document.getElementById('root'));
LIVE DEMO IS HERE
Please for help.
javascript reactjs addeventlistener react-hooks
javascript reactjs addeventlistener react-hooks
edited Mar 24 at 17:27
Edenwave
asked Mar 24 at 17:16
EdenwaveEdenwave
13613
13613
add a comment |
add a comment |
1 Answer
1
active
oldest
votes
Every render you get a new copy of resize
function. Each copy captures the current value of width
. Your listener has a copy which was created on the first render with width = 0
.
To fix this issue you have several options:
Update listeners when
width
changesuseEffect(() =>
resize();
window.addEventListener("resize", resize);
return () => window.removeEventListener("resize", resize);
, [width]);Use functional updates to get the current width inside listener
const resize = () =>
setWidth(oldWidth =>
console.log("width:", oldWidth);
return window.innerWidth
);
;Store the width in a mutable reference
const widthRef = useRef(width);
const resize = () =>
console.log("width:", widthRef.current);
widthRef.current = window.innerWidth;
setWidth(window.innerWidth);
;
Yes it would. The seconduseEffect
won't help with the issue. You either need to remove-add listeners whenwidth
changes or get the current value of thewidth
some other way. Hence 3 possible solutions. The first is just the easiest one.
– UjinT34
Mar 24 at 19:13
Your code has bad optimization and doesn't really help with the original issue. It just hides the problem. FirstuseEffect
sets an event listener which resetswidth
to the initial value. This triggers rerender and the seconduseEffect
. The seconduseEffect
sets thewidth
to a correct value. So each resize event triggers two rerenders instead of one and one of theresize
calls uses the wrong value.
– UjinT34
Mar 24 at 19:39
I love the 3rd way. Thank you.
– Edenwave
Mar 24 at 20:09
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%2f55326406%2freact-hooks-value-is-not-accessible-in-event-listener-function%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
Every render you get a new copy of resize
function. Each copy captures the current value of width
. Your listener has a copy which was created on the first render with width = 0
.
To fix this issue you have several options:
Update listeners when
width
changesuseEffect(() =>
resize();
window.addEventListener("resize", resize);
return () => window.removeEventListener("resize", resize);
, [width]);Use functional updates to get the current width inside listener
const resize = () =>
setWidth(oldWidth =>
console.log("width:", oldWidth);
return window.innerWidth
);
;Store the width in a mutable reference
const widthRef = useRef(width);
const resize = () =>
console.log("width:", widthRef.current);
widthRef.current = window.innerWidth;
setWidth(window.innerWidth);
;
Yes it would. The seconduseEffect
won't help with the issue. You either need to remove-add listeners whenwidth
changes or get the current value of thewidth
some other way. Hence 3 possible solutions. The first is just the easiest one.
– UjinT34
Mar 24 at 19:13
Your code has bad optimization and doesn't really help with the original issue. It just hides the problem. FirstuseEffect
sets an event listener which resetswidth
to the initial value. This triggers rerender and the seconduseEffect
. The seconduseEffect
sets thewidth
to a correct value. So each resize event triggers two rerenders instead of one and one of theresize
calls uses the wrong value.
– UjinT34
Mar 24 at 19:39
I love the 3rd way. Thank you.
– Edenwave
Mar 24 at 20:09
add a comment |
Every render you get a new copy of resize
function. Each copy captures the current value of width
. Your listener has a copy which was created on the first render with width = 0
.
To fix this issue you have several options:
Update listeners when
width
changesuseEffect(() =>
resize();
window.addEventListener("resize", resize);
return () => window.removeEventListener("resize", resize);
, [width]);Use functional updates to get the current width inside listener
const resize = () =>
setWidth(oldWidth =>
console.log("width:", oldWidth);
return window.innerWidth
);
;Store the width in a mutable reference
const widthRef = useRef(width);
const resize = () =>
console.log("width:", widthRef.current);
widthRef.current = window.innerWidth;
setWidth(window.innerWidth);
;
Yes it would. The seconduseEffect
won't help with the issue. You either need to remove-add listeners whenwidth
changes or get the current value of thewidth
some other way. Hence 3 possible solutions. The first is just the easiest one.
– UjinT34
Mar 24 at 19:13
Your code has bad optimization and doesn't really help with the original issue. It just hides the problem. FirstuseEffect
sets an event listener which resetswidth
to the initial value. This triggers rerender and the seconduseEffect
. The seconduseEffect
sets thewidth
to a correct value. So each resize event triggers two rerenders instead of one and one of theresize
calls uses the wrong value.
– UjinT34
Mar 24 at 19:39
I love the 3rd way. Thank you.
– Edenwave
Mar 24 at 20:09
add a comment |
Every render you get a new copy of resize
function. Each copy captures the current value of width
. Your listener has a copy which was created on the first render with width = 0
.
To fix this issue you have several options:
Update listeners when
width
changesuseEffect(() =>
resize();
window.addEventListener("resize", resize);
return () => window.removeEventListener("resize", resize);
, [width]);Use functional updates to get the current width inside listener
const resize = () =>
setWidth(oldWidth =>
console.log("width:", oldWidth);
return window.innerWidth
);
;Store the width in a mutable reference
const widthRef = useRef(width);
const resize = () =>
console.log("width:", widthRef.current);
widthRef.current = window.innerWidth;
setWidth(window.innerWidth);
;
Every render you get a new copy of resize
function. Each copy captures the current value of width
. Your listener has a copy which was created on the first render with width = 0
.
To fix this issue you have several options:
Update listeners when
width
changesuseEffect(() =>
resize();
window.addEventListener("resize", resize);
return () => window.removeEventListener("resize", resize);
, [width]);Use functional updates to get the current width inside listener
const resize = () =>
setWidth(oldWidth =>
console.log("width:", oldWidth);
return window.innerWidth
);
;Store the width in a mutable reference
const widthRef = useRef(width);
const resize = () =>
console.log("width:", widthRef.current);
widthRef.current = window.innerWidth;
setWidth(window.innerWidth);
;
edited Mar 24 at 19:46
answered Mar 24 at 18:09
UjinT34UjinT34
2,1001316
2,1001316
Yes it would. The seconduseEffect
won't help with the issue. You either need to remove-add listeners whenwidth
changes or get the current value of thewidth
some other way. Hence 3 possible solutions. The first is just the easiest one.
– UjinT34
Mar 24 at 19:13
Your code has bad optimization and doesn't really help with the original issue. It just hides the problem. FirstuseEffect
sets an event listener which resetswidth
to the initial value. This triggers rerender and the seconduseEffect
. The seconduseEffect
sets thewidth
to a correct value. So each resize event triggers two rerenders instead of one and one of theresize
calls uses the wrong value.
– UjinT34
Mar 24 at 19:39
I love the 3rd way. Thank you.
– Edenwave
Mar 24 at 20:09
add a comment |
Yes it would. The seconduseEffect
won't help with the issue. You either need to remove-add listeners whenwidth
changes or get the current value of thewidth
some other way. Hence 3 possible solutions. The first is just the easiest one.
– UjinT34
Mar 24 at 19:13
Your code has bad optimization and doesn't really help with the original issue. It just hides the problem. FirstuseEffect
sets an event listener which resetswidth
to the initial value. This triggers rerender and the seconduseEffect
. The seconduseEffect
sets thewidth
to a correct value. So each resize event triggers two rerenders instead of one and one of theresize
calls uses the wrong value.
– UjinT34
Mar 24 at 19:39
I love the 3rd way. Thank you.
– Edenwave
Mar 24 at 20:09
Yes it would. The second
useEffect
won't help with the issue. You either need to remove-add listeners when width
changes or get the current value of the width
some other way. Hence 3 possible solutions. The first is just the easiest one.– UjinT34
Mar 24 at 19:13
Yes it would. The second
useEffect
won't help with the issue. You either need to remove-add listeners when width
changes or get the current value of the width
some other way. Hence 3 possible solutions. The first is just the easiest one.– UjinT34
Mar 24 at 19:13
Your code has bad optimization and doesn't really help with the original issue. It just hides the problem. First
useEffect
sets an event listener which resets width
to the initial value. This triggers rerender and the second useEffect
. The second useEffect
sets the width
to a correct value. So each resize event triggers two rerenders instead of one and one of the resize
calls uses the wrong value.– UjinT34
Mar 24 at 19:39
Your code has bad optimization and doesn't really help with the original issue. It just hides the problem. First
useEffect
sets an event listener which resets width
to the initial value. This triggers rerender and the second useEffect
. The second useEffect
sets the width
to a correct value. So each resize event triggers two rerenders instead of one and one of the resize
calls uses the wrong value.– UjinT34
Mar 24 at 19:39
I love the 3rd way. Thank you.
– Edenwave
Mar 24 at 20:09
I love the 3rd way. Thank you.
– Edenwave
Mar 24 at 20:09
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%2f55326406%2freact-hooks-value-is-not-accessible-in-event-listener-function%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