score:2
Accepted answer
issue
you are enclosing the initial state in the attached callback by only setting the callback when the component mounts using an empty dependency array. a functional state update won't have this issue as it uses a callback function to compute and return a new state value from the previous state value.
solution
- the effect needs to add an event listener correctly. (and return a cleanup function!!)
- state update should be a functional update since it depends on previous state.
- state updates are asynchronous in nature, so alerting or logging it right after it is enqueued will only log the current state value from the current render cycle. use an effect to do anything with the updated state.
updated code
const hello = () => {
const [counter, setcounter] = react.usestate(0);
let canvas = react.useref();
const add = () => {
setcounter(counter => counter + 3);
};
react.useeffect(() => {
console.log(counter); // or alert, if you really want to
}, [counter]);
react.useeffect(() => {
window.addeventlistener("keydown", add);
return () => window.removeeventlistener("keydown", add);
}, []);
return (
<div>
<h1>{counter}</h1>
</div>
);
};
score:0
passing an empty array will trigger the useeffect
only at the mounting of the component, just add the counter in the array in order for it to be triggered every time the state is updated.
react.useeffect(() => {
window.onkeydown = add
}, [counter])
Source: stackoverflow.com
Related Query
- Setting event handlers on react hooks (useEffect)
- React Hooks - Updating state using props without event handlers
- Setting an interval on a click event in React using Hooks won't use updated state values
- React hooks useEffect only on update?
- Event Handlers in React Stateless Components
- Wrong React hooks behaviour with event listener
- Correct way to create event handlers using hooks in React?
- React Hooks - useEffect fires even though the state did not change
- React hooks - trigger useEffect when a nested property changes in a collection of objects
- react hooks props in useEffect
- Does a render happen before function in React Hooks useEffect is called?
- React Hooks - Ref is not avaiable inside useEffect
- How to fix nextCreate is not a function setting up useMemo setting up authentication react router and hooks
- How to clean up setInterval in useEffect using react hooks
- React event handlers with Typescript and JSX
- state inside useEffect refers the initial state always with React Hooks
- React hooks value is not accessible in event listener function
- React Hooks - 0 vs. empty array as second argument in useEffect
- How to attach drag event handlers to a React component using TypeScript
- Unsubscribe from event listener react hooks
- React Testing: Event handlers in React Shallow Rendering unit tests
- Remove event listener manually react hooks
- How to execute store.unsubscribe from useEffect using React hooks and Redux
- Sending event handlers as props into a React component using TypeScript
- Setting an array to null and then updating it in useEffect React
- Pass multiple parameters to event handlers in React
- Event listener functions changing when using React hooks
- Access old state to compare with new state inside useEffect react hook with custom hooks usePrevious
- Currying event handlers in React
- VSCode auto import React built-in hooks like useState, useEffect
More Query from same tag
- React-Redux, error in filtering out item from store
- How can I display elements into each row?
- util.crypto.lib. randomBytes is not a function : aws cognito js throws error on authentication
- How to conect docker nginx with express and react app on windows
- What is the most elegant approch to waiting until a loop ends and than do an operation in Javascript?
- React img src not displaying from aws s3 url
- nock is not intercepting my request
- In React-Konva, How to get the position of a click on an Image-shape in a draggable Stage
- react-pdf generation is very slow in combination with umijs
- "ReferenceError: path is not defined" in my Gatsby project
- seperate python flask files into multiple files
- avoid constant re-render from "input" or "textarea" in react js
- Redux connect / reduxForm will not render Component
- Move function in React from component to referenced library
- How to pass parameter value into modal box with react
- Error: A required parameter (productId) was not provided as a string in getStaticPaths for /products/[productId]
- Setup distinct keys for React Elements within an HOC which renders different components based on props?
- Dynamically wrap text in an anchor tag in Quilljs Error: addRange(): The given range isn't in document
- React Typescript: api data to array map
- React useEffect doesn't block the re-render
- Default route always execute in react router
- How to use material-ui breakpoint rule in external styles?
- Event reference is undefined on event listener callback passed as a method
- How to use react hooks to pass a state from child component to the parent component?
- How to update URL with map coordinates?
- How to change deeply nested states without explicitly providing a lot of context in actions?
- How to track changes of a referenced element with React?
- Redux : reset 1 variable to initial state in Redux
- How do I add a delay on a button click in react?
- How can i grab one of my elements in the array and style it?