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;








0















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.










share|improve this question






























    0















    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.










    share|improve this question


























      0












      0








      0


      1






      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.










      share|improve this question
















      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






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Mar 24 at 17:27







      Edenwave

















      asked Mar 24 at 17:16









      EdenwaveEdenwave

      13613




      13613






















          1 Answer
          1






          active

          oldest

          votes


















          5














          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:




          1. Update listeners when width changes



            useEffect(() => 
            resize();
            window.addEventListener("resize", resize);
            return () => window.removeEventListener("resize", resize);
            , [width]);



          2. Use functional updates to get the current width inside listener



            const resize = () => 
            setWidth(oldWidth =>
            console.log("width:", oldWidth);
            return window.innerWidth
            );
            ;



          3. 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);
            ;






          share|improve this answer

























          • 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












          • I love the 3rd way. Thank you.

            – Edenwave
            Mar 24 at 20:09











          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%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









          5














          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:




          1. Update listeners when width changes



            useEffect(() => 
            resize();
            window.addEventListener("resize", resize);
            return () => window.removeEventListener("resize", resize);
            , [width]);



          2. Use functional updates to get the current width inside listener



            const resize = () => 
            setWidth(oldWidth =>
            console.log("width:", oldWidth);
            return window.innerWidth
            );
            ;



          3. 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);
            ;






          share|improve this answer

























          • 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












          • I love the 3rd way. Thank you.

            – Edenwave
            Mar 24 at 20:09















          5














          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:




          1. Update listeners when width changes



            useEffect(() => 
            resize();
            window.addEventListener("resize", resize);
            return () => window.removeEventListener("resize", resize);
            , [width]);



          2. Use functional updates to get the current width inside listener



            const resize = () => 
            setWidth(oldWidth =>
            console.log("width:", oldWidth);
            return window.innerWidth
            );
            ;



          3. 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);
            ;






          share|improve this answer

























          • 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












          • I love the 3rd way. Thank you.

            – Edenwave
            Mar 24 at 20:09













          5












          5








          5







          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:




          1. Update listeners when width changes



            useEffect(() => 
            resize();
            window.addEventListener("resize", resize);
            return () => window.removeEventListener("resize", resize);
            , [width]);



          2. Use functional updates to get the current width inside listener



            const resize = () => 
            setWidth(oldWidth =>
            console.log("width:", oldWidth);
            return window.innerWidth
            );
            ;



          3. 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);
            ;






          share|improve this answer















          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:




          1. Update listeners when width changes



            useEffect(() => 
            resize();
            window.addEventListener("resize", resize);
            return () => window.removeEventListener("resize", resize);
            , [width]);



          2. Use functional updates to get the current width inside listener



            const resize = () => 
            setWidth(oldWidth =>
            console.log("width:", oldWidth);
            return window.innerWidth
            );
            ;



          3. 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);
            ;







          share|improve this answer














          share|improve this answer



          share|improve this answer








          edited Mar 24 at 19:46

























          answered Mar 24 at 18:09









          UjinT34UjinT34

          2,1001316




          2,1001316












          • 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












          • 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











          • 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
















          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

















          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%2f55326406%2freact-hooks-value-is-not-accessible-in-event-listener-function%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

          Kamusi Yaliyomo Aina za kamusi | Muundo wa kamusi | Faida za kamusi | Dhima ya picha katika kamusi | Marejeo | Tazama pia | Viungo vya nje | UrambazajiKuhusu kamusiGo-SwahiliWiki-KamusiKamusi ya Kiswahili na Kiingerezakuihariri na kuongeza habari

          Swift 4 - func physicsWorld not invoked on collision? The Next CEO of Stack OverflowHow to call Objective-C code from Swift#ifdef replacement in the Swift language@selector() in Swift?#pragma mark in Swift?Swift for loop: for index, element in array?dispatch_after - GCD in Swift?Swift Beta performance: sorting arraysSplit a String into an array in Swift?The use of Swift 3 @objc inference in Swift 4 mode is deprecated?How to optimize UITableViewCell, because my UITableView lags

          Access current req object everywhere in Node.js ExpressWhy are global variables considered bad practice? (node.js)Using req & res across functionsHow do I get the path to the current script with Node.js?What is Node.js' Connect, Express and “middleware”?Node.js w/ express error handling in callbackHow to access the GET parameters after “?” in Express?Modify Node.js req object parametersAccess “app” variable inside of ExpressJS/ConnectJS middleware?Node.js Express app - request objectAngular Http Module considered middleware?Session variables in ExpressJSAdd properties to the req object in expressjs with Typescript