score:0
the best way to go about such scenarios is to see what you are doing in the event handler. if you are simply setting a state using the previous state, it's best to use the callback pattern and register the event listeners only on the initial mount. if you do not use the callback pattern (https://reactjs.org/docs/hooks-reference.html#usecallback) the listeners reference along with its lexical scope is being used by the event listener but a new function is created with updated closure on new render and hence in the handler you will not be able to the updated state
const [usertext, setusertext] = usestate('');
const handleuserkeypress = usecallback(event => {
const { key, keycode } = event;
if (keycode === 32 || (keycode >= 65 && keycode <= 90)) {
setusertext(prevusertext => `${prevusertext}${key}`);
}
}, []);
useeffect(() => {
window.addeventlistener('keydown', handleuserkeypress);
return () => {
window.removeeventlistener('keydown', handleuserkeypress);
};
}, [handleuserkeypress]);
return (
<div>
<h1>feel free to type!</h1>
<blockquote>{usertext}</blockquote>
</div>
);
according to this answer : https://stackoverflow.com/a/55566585/6845743
score:0
i think i figured out the issue, it was entirely my fault and the way i wrote my component.
minimal example https://codesandbox.io/s/strange-nobel-l6eqe?file=/src/app.js
it's a lot more obvious here, but essentially the component where the listener was created wasn't actually being unmounted, i was just unmounting its contents which obviously meant the listener wasn't getting removed.
solutions are:
- don't write your component like this
- move the listener inside a child component
score:0
keep the handler outside useeffect, that should work. we would just be attaching that function on mount and removing on unmount.
const component = () => {
const handler = (e: keyboardevent) => {
if (e.iscomposing || e.keycode === 27) {
console.log('do something');
}
};
useeffect(() => {
window.addeventlistener('keydown', handler, false);
return () => window.removeeventlistener('keydown', handler, false);
}, []);
return <div />;
};
Source: stackoverflow.com
Related Query
- How to add event listener to the div element accessed with ref using react and typescript?
- Can we trigger KeyPress on Div Tag in react
- React: Keypress listener on div
- Wrong React hooks behaviour with event listener
- Detecting when user scrolls to bottom of div with React js
- Why can't I change my input value in React even with the onChange listener
- Why can't I change my input value in React even with the onChange listener
- Remove Event Listener On Unmount React
- Scroll to bottom of an overflowing div in React
- How do you center a div element in react w/out external css file
- React testing library - check the existence of empty div
- react open file browser on click a div
- Firebase listener with React Hooks
- Expected onClick listener to be a function, instead got type object - react redux
- Focusing div elements with React
- React SVG component as background-image to div
- React setState hook from scroll event listener
- How to remove the new firebase onAuthStateChanged listener in react
- How to simulate mouse over event on a div using enzyme for testing a react application?
- how to hide and show a div in react
- Best way to disabled DIV onClick in React
- React - Get text of div on click without refs
- React navigation didfocus event listener works differently between class component and functional component
- Removing event listener in React (lodash.throttle)
- react scrolling a div by dragging the mouse?
- React hooks value is not accessible in event listener function
- Using transitionend event listener with react to create a transition
- Unsubscribe from event listener react hooks
- React unable to focus on div
- React.JS - Manage content of contenteditable div as React components
More Query from same tag
- How do I get Promises to work when using Jest CLI?
- React: Display an image converted to base64
- How to make a React App windows Authentication
- Use typescript with react-intl
- How to sum up data in the rendered component in react?
- How to sort ant table column by date?
- I am using reactJS, AntD Table for framework, but I can't make the data shown in the table
- lazy load for dynamic component test coverage
- Matching routes with hyphens in react-router
- Putting two functions in the same "onclick"
- How to prevent reloading in React?
- trying to set the value of a field but it is not working
- "No overload matches this call" error when setting up ContextApi & useReducer using Typescript
- How to add extra stroke in Material-UI Circular Progress
- How to override MUI 5 input label background color for custom component
- React stale state issue with callback passed to children
- How do you create a multi-page application using React?
- Why React npm start return error for webpack-dev-server 3.11.1?
- Move a specific part of text to next line if it have to
- HOC as an App Wrapper for React Redux
- Invalid prop `component` of type `object` supplied to `Route`, expected `function`
- I'm getting error after upgrading to Material UI 4 - withStyles
- Framer motion Animate Presence exit issue
- React DatePicker calendar showing behind table head
- How to properly declare a module for React and Require without Node?
- How to test react component with axios request in useEffect?
- Display React Bootstrap's Modal when you press a button
- In ReactJS how do I keep track of the state of a group of checkboxes?
- React Not returning Child from map loop when creating SVG from JSON object
- Is there an appropriate way to reuse Redux aware components?