Closed abhijithvijayan closed 5 years ago
In your useEffect
you should provide the missing dependency.
Here is a minimal example.
import throttle from "lodash.throttle";
function App() {
let [state, setState] = React.useState("No key pressed yet.");
const handleEvent = throttle(event => {
console.log(state);
setState(event.code);
}, 50);
React.useEffect(() => {
window.addEventListener("keyup", handleEvent);
return () => window.removeEventListener("keyup", handleEvent);
}, [handleEvent]); // <--------- provide the dependency
return (
<div className="app">
<h1>Press a key</h1>
{state}
</div>
);
}
https://codesandbox.io/s/react-useeffect-event-listener-dependency-example-uhnwq
@kunukn It keeps on looping
@abhijithvijayan It would be helpful if you provided a complete, runnable repro in Code Sandbox. The above example seems to be missing some context. However...
State values is somehow reset to initial values when used under an arrow function that is defined under a functional component when using hooks.
It sounds like you're saying that you're creating a component inside of another component, which is probably never a good idea. For example:
const Foo = props => {
const Bar = barProps => {
// ...
};
// ...
};
Each time Foo
is rendered, it will create a new Bar
component (a new function). React sees this new function as a completely new component type, so it will unmount the previous Bar
(and anything it renders- all of its children) and re-initialize and re-mount the new Bar
. I don't think this would ever be what you want.
I assume my response above helps answer this issue, so I'm going to close it. If not, please provide a full repro case (that we can actually run and see all of the pieces) and I'll take a look.
Do you want to request a feature or report a bug? I'm not sure if it's a bug or it is supposed to work that way.
What is the current behavior? State values is somehow reset to initial values when used under an arrow function that is defined under a functional component when using hooks.
What is the expected behavior? The bindings should be the same isn't it? It worked perfectly when I was using class component with lifecycle methods.
Which versions of React, and which browser / OS are affected by this issue? Did this work in previous versions of React?
React: 16.9.0 Browser: Chrome 76.0.3809.132 OS: Ubuntu 18.04