0
import "./styles.css";
import React , {useEffect,useState} from 'react'

export default function App() {
  const [state,setState] = useState(0)
  const handleUserKeyPress=(e)=>{
    console.log(state);   // this console prints 0 each time no update here ...

    setState(prev=>Number(prev)+1)
  }
  useEffect(() => {

    window.addEventListener('keydown', handleUserKeyPress);
  
    return () => {
      window.removeEventListener('keydown', handleUserKeyPress);
    };
  }, []);
  return (
    <div className="App">
      <h1>Hello CodeSandbox {state}</h1>
      <h2>Start editing to see some magic happen!</h2>
    </div>
  );
}

value of state is updated on dom but when I am doing a console.log I am getting the value 0 which is initialised at the beginning .

Sandbox link for the same link

Hritik Sharma
  • 1,756
  • 7
  • 24
  • 1
    Put `state` inside the useEffect dependency array? – evolutionxbox Apr 19 '22 at 07:32
  • My question is , changes are seen in the DOM but not in the console.log... – Hritik Sharma Apr 19 '22 at 07:33
  • 1
    @Prana the OP is, `setState(...)` – evolutionxbox Apr 19 '22 at 07:34
  • setState is doing that – Hritik Sharma Apr 19 '22 at 07:34
  • 2
    There **has** to be a good original question to point this at. @​Hritik, the problem is that the first version of `handleUserKeyPress` (created by the render on first mount) closes over the first version of the `state` constant, which will never change. But the **state** value -- what you get back from `useState` -- **will** change as desired. The value to log isn't `state` (you shouldn't be using possibly-stale variables in that function), but `prev` (or `prev+1`) in your `setState` callback. You'll see it increase there. – T.J. Crowder Apr 19 '22 at 07:34
  • `handleUserKeyPress` isn't being reattached when the state is updated. Add `state` to the `useEffect`. – evolutionxbox Apr 19 '22 at 07:35
  • 1
    (Side note: There's no reason to use `Number(prev)`, `prev` is *already* a number.) – T.J. Crowder Apr 19 '22 at 07:36
  • puttinf state inside dependency array gives me 2 console.logs – Hritik Sharma Apr 19 '22 at 07:38
  • There is a warning for `useEffect()` second parameter being an empty array in the sandbox link that you provide. That warning tells you to enter something in the array or exclude the second parameter altogether. Deleting ,[] and the counter increment correctly. – John Apr 19 '22 at 07:43
  • The next error you should then see says _"The 'handleUserKeyPress' function makes the dependencies of useEffect Hook (at line 17) change on every render. **Move it inside the useEffect callback.** Alternatively, wrap the definition of 'handleUserKeyPress' in its own useCallback() Hook."_ – evolutionxbox Apr 19 '22 at 07:45
  • Understood ! Thanks a lot . – Hritik Sharma Apr 19 '22 at 07:52

0 Answers0