How to register event with useEffect hooks?How do JavaScript closures work?How do I check if an element is...
Finding files for which a command fails
cryptic clue: mammal sounds like relative consumer (8)
Why is an old chain unsafe?
Why do we use polarized capacitor?
Why is "Reports" in sentence down without "The"
What typically incentivizes a professor to change jobs to a lower ranking university?
Why has Russell's definition of numbers using equivalence classes been finally abandoned? ( If it has actually been abandoned).
Are tax years 2016 & 2017 back taxes deductible for tax year 2018?
How can the DM most effectively choose 1 out of an odd number of players to be targeted by an attack or effect?
How to make payment on the internet without leaving a money trail?
Motorized valve interfering with button?
how to create a data type and make it available in all Databases?
Download, install and reboot computer at night if needed
How is it possible for user's password to be changed after storage was encrypted? (on OS X, Android)
How can bays and straits be determined in a procedurally generated map?
Showing the closure of a compact subset need not be compact
What is the white spray-pattern residue inside these Falcon Heavy nozzles?
How does one intimidate enemies without having the capacity for violence?
A newer friend of my brother's gave him a load of baseball cards that are supposedly extremely valuable. Is this a scam?
How do I create uniquely male characters?
"The augmented fourth (A4) and the diminished fifth (d5) are the only augmented and diminished intervals that appear in diatonic scales"
Why Is Death Allowed In the Matrix?
Is Social Media Science Fiction?
Schwarzchild Radius of the Universe
How to register event with useEffect hooks?
How do JavaScript closures work?How do I check if an element is hidden in jQuery?How do I remove a property from a JavaScript object?How do I redirect to another webpage?How do I include a JavaScript file in another JavaScript file?How to replace all occurrences of a string in JavaScriptHow to check whether a string contains a substring in JavaScript?How do I remove a particular element from an array in JavaScript?How to use foreach with array in JavaScript?How do I return the response from an asynchronous call?
.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty{ height:90px;width:728px;box-sizing:border-box;
}
Following some Udemy course on how to register events with hooks, the instructor gave the below code:
const [userText, setUserText] = useState('');
const handleUserKeyPress = event => {
const { key, keyCode } = event;
if (keyCode === 32 || (keyCode >= 65 && keyCode <= 90)) {
setUserText(`${userText}${key}`);
}
};
useEffect(() => {
window.addEventListener('keydown', handleUserKeyPress);
return () => {
window.removeEventListener('keydown', handleUserKeyPress);
};
});
return (
<div>
<h1>Feel free to type!</h1>
<blockquote>{userText}</blockquote>
</div>
);
Now it works great but I'm not convinced that this is the right way. The reason is, if I understand correctly, on each and every re-render, events will keep registering and deregistering every time and I simply don't think is the right way to go about it.
So I made a slight modification to the useEffect
hooks to below
useEffect(() => {
window.addEventListener('keydown', handleUserKeyPress);
return () => {
window.removeEventListener('keydown', handleUserKeyPress);
};
}, []);
By having an empty array as the second argument, letting the component to only run the effect once, imitating componentDidMount
. And when I try out the result, it's weird that on every key I type, instead of appending, it's overwritten instead.
I was expecting setUserText(${userText}${key}
); to have new typed key append to current state and set as a new state but instead, it's forgetting the old state and rewriting with the new state.
Was it really the correct way that we should register and deregister event on every re-render?
javascript reactjs react-hooks
add a comment |
Following some Udemy course on how to register events with hooks, the instructor gave the below code:
const [userText, setUserText] = useState('');
const handleUserKeyPress = event => {
const { key, keyCode } = event;
if (keyCode === 32 || (keyCode >= 65 && keyCode <= 90)) {
setUserText(`${userText}${key}`);
}
};
useEffect(() => {
window.addEventListener('keydown', handleUserKeyPress);
return () => {
window.removeEventListener('keydown', handleUserKeyPress);
};
});
return (
<div>
<h1>Feel free to type!</h1>
<blockquote>{userText}</blockquote>
</div>
);
Now it works great but I'm not convinced that this is the right way. The reason is, if I understand correctly, on each and every re-render, events will keep registering and deregistering every time and I simply don't think is the right way to go about it.
So I made a slight modification to the useEffect
hooks to below
useEffect(() => {
window.addEventListener('keydown', handleUserKeyPress);
return () => {
window.removeEventListener('keydown', handleUserKeyPress);
};
}, []);
By having an empty array as the second argument, letting the component to only run the effect once, imitating componentDidMount
. And when I try out the result, it's weird that on every key I type, instead of appending, it's overwritten instead.
I was expecting setUserText(${userText}${key}
); to have new typed key append to current state and set as a new state but instead, it's forgetting the old state and rewriting with the new state.
Was it really the correct way that we should register and deregister event on every re-render?
javascript reactjs react-hooks
add a comment |
Following some Udemy course on how to register events with hooks, the instructor gave the below code:
const [userText, setUserText] = useState('');
const handleUserKeyPress = event => {
const { key, keyCode } = event;
if (keyCode === 32 || (keyCode >= 65 && keyCode <= 90)) {
setUserText(`${userText}${key}`);
}
};
useEffect(() => {
window.addEventListener('keydown', handleUserKeyPress);
return () => {
window.removeEventListener('keydown', handleUserKeyPress);
};
});
return (
<div>
<h1>Feel free to type!</h1>
<blockquote>{userText}</blockquote>
</div>
);
Now it works great but I'm not convinced that this is the right way. The reason is, if I understand correctly, on each and every re-render, events will keep registering and deregistering every time and I simply don't think is the right way to go about it.
So I made a slight modification to the useEffect
hooks to below
useEffect(() => {
window.addEventListener('keydown', handleUserKeyPress);
return () => {
window.removeEventListener('keydown', handleUserKeyPress);
};
}, []);
By having an empty array as the second argument, letting the component to only run the effect once, imitating componentDidMount
. And when I try out the result, it's weird that on every key I type, instead of appending, it's overwritten instead.
I was expecting setUserText(${userText}${key}
); to have new typed key append to current state and set as a new state but instead, it's forgetting the old state and rewriting with the new state.
Was it really the correct way that we should register and deregister event on every re-render?
javascript reactjs react-hooks
Following some Udemy course on how to register events with hooks, the instructor gave the below code:
const [userText, setUserText] = useState('');
const handleUserKeyPress = event => {
const { key, keyCode } = event;
if (keyCode === 32 || (keyCode >= 65 && keyCode <= 90)) {
setUserText(`${userText}${key}`);
}
};
useEffect(() => {
window.addEventListener('keydown', handleUserKeyPress);
return () => {
window.removeEventListener('keydown', handleUserKeyPress);
};
});
return (
<div>
<h1>Feel free to type!</h1>
<blockquote>{userText}</blockquote>
</div>
);
Now it works great but I'm not convinced that this is the right way. The reason is, if I understand correctly, on each and every re-render, events will keep registering and deregistering every time and I simply don't think is the right way to go about it.
So I made a slight modification to the useEffect
hooks to below
useEffect(() => {
window.addEventListener('keydown', handleUserKeyPress);
return () => {
window.removeEventListener('keydown', handleUserKeyPress);
};
}, []);
By having an empty array as the second argument, letting the component to only run the effect once, imitating componentDidMount
. And when I try out the result, it's weird that on every key I type, instead of appending, it's overwritten instead.
I was expecting setUserText(${userText}${key}
); to have new typed key append to current state and set as a new state but instead, it's forgetting the old state and rewriting with the new state.
Was it really the correct way that we should register and deregister event on every re-render?
javascript reactjs react-hooks
javascript reactjs react-hooks
edited 2 hours ago
bennygenel
13.2k32751
13.2k32751
asked 4 hours ago
IsaacIsaac
3,7792830
3,7792830
add a comment |
add a comment |
6 Answers
6
active
oldest
votes
The best way to go about such scenarios is to see what you are doing in the event handler. If you are simply setting state using previous state, its best to use the callback pattern and register the event listeners only on initial mount. If you do not use the callback pattern
the 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 = 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);
};
}, []);
return (
<div>
<h1>Feel free to type!</h1>
<blockquote>{userText}</blockquote>
</div>
);
Your solution makes most sense to me as compared to others, thanks a lot!
– Isaac
1 hour ago
Glad to have helped (y)
– Shubham Khatri
48 mins ago
add a comment |
You'll need a way to keep track of the previous state. useState
helps you keep track of the current state only. From the docs, there is a way to access the old state, by using another hook.
const prevRef = useRef();
useEffect(() => {
prevRef.current = userText;
});
I've updated your example to use this. And it works out.
const { useState, useEffect, useRef } = React;
const App = () => {
const [userText, setUserText] = useState("");
const prevRef = useRef();
useEffect(() => {
prevRef.current = userText;
});
const handleUserKeyPress = event => {
const { key, keyCode } = event;
if (keyCode === 32 || (keyCode >= 65 && keyCode <= 90)) {
setUserText(`${prevRef.current}${key}`);
}
};
useEffect(() => {
window.addEventListener("keydown", handleUserKeyPress);
return () => {
window.removeEventListener("keydown", handleUserKeyPress);
};
}, []);
return (
<div>
<h1>Feel free to type!</h1>
<blockquote>{userText}</blockquote>
</div>
);
};
ReactDOM.render(<App />, document.getElementById("root"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.3/umd/react-dom.production.min.js"></script>
<div id="root"></div>
add a comment |
In the second approach, the useEffect
is bound only once and hence the userText
never gets updated. One approach would be to maintain a local variable which gets updated along with the userText
object on every keypress.
const [userText, setUserText] = useState('');
let local_text = userText
const handleUserKeyPress = event => {
const { key, keyCode } = event;
if (keyCode === 32 || (keyCode >= 65 && keyCode <= 90)) {
local_text = `${userText}${key}`;
setUserText(local_text);
}
};
useEffect(() => {
window.addEventListener('keydown', handleUserKeyPress);
return () => {
window.removeEventListener('keydown', handleUserKeyPress);
};
}, []);
return (
<div>
<h1>Feel free to type!</h1>
<blockquote>{userText}</blockquote>
</div>
);
Personally I don't like the solution, feels anti-react
and I think the first method is good enough and is designed to be used that way.
Do you mind to include some code to demonstrate how to achieve my objective in second method?
– Isaac
4 hours ago
add a comment |
try this, it works same as your original code:
useEffect(() => {
function handlekeydownEvent(event) {
const { key, keyCode } = event;
if (keyCode === 32 || (keyCode >= 65 && keyCode <= 90)) {
setUserText(`${userText}${key}`);
}
}
document.addEventListener('keyup', handlekeydownEvent)
return () => {
document.removeEventListener('keyup', handlekeydownEvent)
}
}, [userText])
because in your useEffect()
method, it depends on the userText
variable but you don't put it inside the second argument, else the userText
will always be bound to the initial value ''
with argument []
.
you don't need to do like this, just want to let you know why your second solution doesn't work.
By adding[userText]
is exactly the same as without second argument, right? Reason is I only haveuserText
in the above example, and without second argument simply means re-rerender on every props/state changes, I don't see how it answer my question. **P/S: ** I'm not the downvoter, thanks for your answer anyway
– Isaac
4 hours ago
hey @Isaac , yep, it is same as without second argument, I just want to let you know why your second solution doesn't work, because your second solutionuseEffect()
depend on theuserText
variable but you didn't put inside the second arguments.
– Spark.Bao
3 hours ago
But by adding in[userText]
, it also means register and deregister the event on every re-render right?
– Isaac
3 hours ago
exactly! that why I say it is same with your first solution.
– Spark.Bao
3 hours ago
1
got what you mean, if you really want to register it only one time in this example, then you need to useuseRef
, just as @Maaz Syed Adeeb 's answer.
– Spark.Bao
3 hours ago
|
show 4 more comments
you dont have access to the changed useText state. you can comapre it to the prevState. store the state in a variable e.g.: state like so:
const [userText, setUserText] = useState('');
let state = ''
const handleUserKeyPress = event => {
const { key, keyCode } = event;
if (keyCode === 32 || (keyCode >= 65 && keyCode <= 90)) {
state += `${key}`
setUserText(state);
}
};
useEffect(() => {
window.addEventListener('keydown', handleUserKeyPress);
return () => {
window.removeEventListener('keydown', handleUserKeyPress);
};
}, []);
return (
<div>
<h1>Feel free to type!</h1>
<blockquote>{userText}</blockquote>
</div>
);
add a comment |
For your use case, useEffect
needs a dependency array to track changes and based on the dependency it can determine whether to re-render or not. It is always advised to pass a dependency array to useEffect
. Kindly see the code below:
I have introduced useCallback
hook.
const { useCallback, useState, useEffect } = React;
function App() {
const [userText, setUserText] = useState('');
const handleUserKeyPress = useCallback(event => {
const { key, keyCode } = event;
if (keyCode === 32 || (keyCode >= 65 && keyCode <= 90)) {
setUserText(`${userText}${key}`);
}
}, [userText]);
useEffect(() => {
window.addEventListener('keydown', handleUserKeyPress);
return () => {
window.removeEventListener('keydown', handleUserKeyPress);
};
}, [handleUserKeyPress]);
return (
<div>
<blockquote>{userText}</blockquote>
</div>
);
}
I've tried your solution, but it's exactly the same as[userText]
or without second argument. Basically we put aconsole.log
insideuseEffect
, we will see that the logging is firing every re-render, which also means,addEventListender
is running every re-render
– Isaac
3 hours ago
I want to believe that is an expected behaviour. I updated my answer.
– John Kennedy
3 hours ago
On your sandbox, you've put a statementconsole.log('>');
withinuseEffect
hooks, and by using your updated code, it's still logging everytime, which also means the events are still registering on every re-render
– Isaac
3 hours ago
1
but because ofreturn () => {window.removeEventListener('keydown', handleUserKeyPress)}
, on every re-render, the component will register and deregister
– Isaac
2 hours ago
1
Exactly the behaviour that I wished for, but you can observe it @ codesandbox.io/s/n5j7qy051j
– Isaac
2 hours ago
|
show 2 more comments
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
});
}
});
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55565444%2fhow-to-register-event-with-useeffect-hooks%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
6 Answers
6
active
oldest
votes
6 Answers
6
active
oldest
votes
active
oldest
votes
active
oldest
votes
The best way to go about such scenarios is to see what you are doing in the event handler. If you are simply setting state using previous state, its best to use the callback pattern and register the event listeners only on initial mount. If you do not use the callback pattern
the 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 = 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);
};
}, []);
return (
<div>
<h1>Feel free to type!</h1>
<blockquote>{userText}</blockquote>
</div>
);
Your solution makes most sense to me as compared to others, thanks a lot!
– Isaac
1 hour ago
Glad to have helped (y)
– Shubham Khatri
48 mins ago
add a comment |
The best way to go about such scenarios is to see what you are doing in the event handler. If you are simply setting state using previous state, its best to use the callback pattern and register the event listeners only on initial mount. If you do not use the callback pattern
the 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 = 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);
};
}, []);
return (
<div>
<h1>Feel free to type!</h1>
<blockquote>{userText}</blockquote>
</div>
);
Your solution makes most sense to me as compared to others, thanks a lot!
– Isaac
1 hour ago
Glad to have helped (y)
– Shubham Khatri
48 mins ago
add a comment |
The best way to go about such scenarios is to see what you are doing in the event handler. If you are simply setting state using previous state, its best to use the callback pattern and register the event listeners only on initial mount. If you do not use the callback pattern
the 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 = 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);
};
}, []);
return (
<div>
<h1>Feel free to type!</h1>
<blockquote>{userText}</blockquote>
</div>
);
The best way to go about such scenarios is to see what you are doing in the event handler. If you are simply setting state using previous state, its best to use the callback pattern and register the event listeners only on initial mount. If you do not use the callback pattern
the 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 = 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);
};
}, []);
return (
<div>
<h1>Feel free to type!</h1>
<blockquote>{userText}</blockquote>
</div>
);
answered 1 hour ago
Shubham KhatriShubham Khatri
95.7k15121161
95.7k15121161
Your solution makes most sense to me as compared to others, thanks a lot!
– Isaac
1 hour ago
Glad to have helped (y)
– Shubham Khatri
48 mins ago
add a comment |
Your solution makes most sense to me as compared to others, thanks a lot!
– Isaac
1 hour ago
Glad to have helped (y)
– Shubham Khatri
48 mins ago
Your solution makes most sense to me as compared to others, thanks a lot!
– Isaac
1 hour ago
Your solution makes most sense to me as compared to others, thanks a lot!
– Isaac
1 hour ago
Glad to have helped (y)
– Shubham Khatri
48 mins ago
Glad to have helped (y)
– Shubham Khatri
48 mins ago
add a comment |
You'll need a way to keep track of the previous state. useState
helps you keep track of the current state only. From the docs, there is a way to access the old state, by using another hook.
const prevRef = useRef();
useEffect(() => {
prevRef.current = userText;
});
I've updated your example to use this. And it works out.
const { useState, useEffect, useRef } = React;
const App = () => {
const [userText, setUserText] = useState("");
const prevRef = useRef();
useEffect(() => {
prevRef.current = userText;
});
const handleUserKeyPress = event => {
const { key, keyCode } = event;
if (keyCode === 32 || (keyCode >= 65 && keyCode <= 90)) {
setUserText(`${prevRef.current}${key}`);
}
};
useEffect(() => {
window.addEventListener("keydown", handleUserKeyPress);
return () => {
window.removeEventListener("keydown", handleUserKeyPress);
};
}, []);
return (
<div>
<h1>Feel free to type!</h1>
<blockquote>{userText}</blockquote>
</div>
);
};
ReactDOM.render(<App />, document.getElementById("root"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.3/umd/react-dom.production.min.js"></script>
<div id="root"></div>
add a comment |
You'll need a way to keep track of the previous state. useState
helps you keep track of the current state only. From the docs, there is a way to access the old state, by using another hook.
const prevRef = useRef();
useEffect(() => {
prevRef.current = userText;
});
I've updated your example to use this. And it works out.
const { useState, useEffect, useRef } = React;
const App = () => {
const [userText, setUserText] = useState("");
const prevRef = useRef();
useEffect(() => {
prevRef.current = userText;
});
const handleUserKeyPress = event => {
const { key, keyCode } = event;
if (keyCode === 32 || (keyCode >= 65 && keyCode <= 90)) {
setUserText(`${prevRef.current}${key}`);
}
};
useEffect(() => {
window.addEventListener("keydown", handleUserKeyPress);
return () => {
window.removeEventListener("keydown", handleUserKeyPress);
};
}, []);
return (
<div>
<h1>Feel free to type!</h1>
<blockquote>{userText}</blockquote>
</div>
);
};
ReactDOM.render(<App />, document.getElementById("root"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.3/umd/react-dom.production.min.js"></script>
<div id="root"></div>
add a comment |
You'll need a way to keep track of the previous state. useState
helps you keep track of the current state only. From the docs, there is a way to access the old state, by using another hook.
const prevRef = useRef();
useEffect(() => {
prevRef.current = userText;
});
I've updated your example to use this. And it works out.
const { useState, useEffect, useRef } = React;
const App = () => {
const [userText, setUserText] = useState("");
const prevRef = useRef();
useEffect(() => {
prevRef.current = userText;
});
const handleUserKeyPress = event => {
const { key, keyCode } = event;
if (keyCode === 32 || (keyCode >= 65 && keyCode <= 90)) {
setUserText(`${prevRef.current}${key}`);
}
};
useEffect(() => {
window.addEventListener("keydown", handleUserKeyPress);
return () => {
window.removeEventListener("keydown", handleUserKeyPress);
};
}, []);
return (
<div>
<h1>Feel free to type!</h1>
<blockquote>{userText}</blockquote>
</div>
);
};
ReactDOM.render(<App />, document.getElementById("root"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.3/umd/react-dom.production.min.js"></script>
<div id="root"></div>
You'll need a way to keep track of the previous state. useState
helps you keep track of the current state only. From the docs, there is a way to access the old state, by using another hook.
const prevRef = useRef();
useEffect(() => {
prevRef.current = userText;
});
I've updated your example to use this. And it works out.
const { useState, useEffect, useRef } = React;
const App = () => {
const [userText, setUserText] = useState("");
const prevRef = useRef();
useEffect(() => {
prevRef.current = userText;
});
const handleUserKeyPress = event => {
const { key, keyCode } = event;
if (keyCode === 32 || (keyCode >= 65 && keyCode <= 90)) {
setUserText(`${prevRef.current}${key}`);
}
};
useEffect(() => {
window.addEventListener("keydown", handleUserKeyPress);
return () => {
window.removeEventListener("keydown", handleUserKeyPress);
};
}, []);
return (
<div>
<h1>Feel free to type!</h1>
<blockquote>{userText}</blockquote>
</div>
);
};
ReactDOM.render(<App />, document.getElementById("root"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.3/umd/react-dom.production.min.js"></script>
<div id="root"></div>
const { useState, useEffect, useRef } = React;
const App = () => {
const [userText, setUserText] = useState("");
const prevRef = useRef();
useEffect(() => {
prevRef.current = userText;
});
const handleUserKeyPress = event => {
const { key, keyCode } = event;
if (keyCode === 32 || (keyCode >= 65 && keyCode <= 90)) {
setUserText(`${prevRef.current}${key}`);
}
};
useEffect(() => {
window.addEventListener("keydown", handleUserKeyPress);
return () => {
window.removeEventListener("keydown", handleUserKeyPress);
};
}, []);
return (
<div>
<h1>Feel free to type!</h1>
<blockquote>{userText}</blockquote>
</div>
);
};
ReactDOM.render(<App />, document.getElementById("root"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.3/umd/react-dom.production.min.js"></script>
<div id="root"></div>
const { useState, useEffect, useRef } = React;
const App = () => {
const [userText, setUserText] = useState("");
const prevRef = useRef();
useEffect(() => {
prevRef.current = userText;
});
const handleUserKeyPress = event => {
const { key, keyCode } = event;
if (keyCode === 32 || (keyCode >= 65 && keyCode <= 90)) {
setUserText(`${prevRef.current}${key}`);
}
};
useEffect(() => {
window.addEventListener("keydown", handleUserKeyPress);
return () => {
window.removeEventListener("keydown", handleUserKeyPress);
};
}, []);
return (
<div>
<h1>Feel free to type!</h1>
<blockquote>{userText}</blockquote>
</div>
);
};
ReactDOM.render(<App />, document.getElementById("root"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.3/umd/react-dom.production.min.js"></script>
<div id="root"></div>
answered 3 hours ago
Maaz Syed AdeebMaaz Syed Adeeb
2,65721426
2,65721426
add a comment |
add a comment |
In the second approach, the useEffect
is bound only once and hence the userText
never gets updated. One approach would be to maintain a local variable which gets updated along with the userText
object on every keypress.
const [userText, setUserText] = useState('');
let local_text = userText
const handleUserKeyPress = event => {
const { key, keyCode } = event;
if (keyCode === 32 || (keyCode >= 65 && keyCode <= 90)) {
local_text = `${userText}${key}`;
setUserText(local_text);
}
};
useEffect(() => {
window.addEventListener('keydown', handleUserKeyPress);
return () => {
window.removeEventListener('keydown', handleUserKeyPress);
};
}, []);
return (
<div>
<h1>Feel free to type!</h1>
<blockquote>{userText}</blockquote>
</div>
);
Personally I don't like the solution, feels anti-react
and I think the first method is good enough and is designed to be used that way.
Do you mind to include some code to demonstrate how to achieve my objective in second method?
– Isaac
4 hours ago
add a comment |
In the second approach, the useEffect
is bound only once and hence the userText
never gets updated. One approach would be to maintain a local variable which gets updated along with the userText
object on every keypress.
const [userText, setUserText] = useState('');
let local_text = userText
const handleUserKeyPress = event => {
const { key, keyCode } = event;
if (keyCode === 32 || (keyCode >= 65 && keyCode <= 90)) {
local_text = `${userText}${key}`;
setUserText(local_text);
}
};
useEffect(() => {
window.addEventListener('keydown', handleUserKeyPress);
return () => {
window.removeEventListener('keydown', handleUserKeyPress);
};
}, []);
return (
<div>
<h1>Feel free to type!</h1>
<blockquote>{userText}</blockquote>
</div>
);
Personally I don't like the solution, feels anti-react
and I think the first method is good enough and is designed to be used that way.
Do you mind to include some code to demonstrate how to achieve my objective in second method?
– Isaac
4 hours ago
add a comment |
In the second approach, the useEffect
is bound only once and hence the userText
never gets updated. One approach would be to maintain a local variable which gets updated along with the userText
object on every keypress.
const [userText, setUserText] = useState('');
let local_text = userText
const handleUserKeyPress = event => {
const { key, keyCode } = event;
if (keyCode === 32 || (keyCode >= 65 && keyCode <= 90)) {
local_text = `${userText}${key}`;
setUserText(local_text);
}
};
useEffect(() => {
window.addEventListener('keydown', handleUserKeyPress);
return () => {
window.removeEventListener('keydown', handleUserKeyPress);
};
}, []);
return (
<div>
<h1>Feel free to type!</h1>
<blockquote>{userText}</blockquote>
</div>
);
Personally I don't like the solution, feels anti-react
and I think the first method is good enough and is designed to be used that way.
In the second approach, the useEffect
is bound only once and hence the userText
never gets updated. One approach would be to maintain a local variable which gets updated along with the userText
object on every keypress.
const [userText, setUserText] = useState('');
let local_text = userText
const handleUserKeyPress = event => {
const { key, keyCode } = event;
if (keyCode === 32 || (keyCode >= 65 && keyCode <= 90)) {
local_text = `${userText}${key}`;
setUserText(local_text);
}
};
useEffect(() => {
window.addEventListener('keydown', handleUserKeyPress);
return () => {
window.removeEventListener('keydown', handleUserKeyPress);
};
}, []);
return (
<div>
<h1>Feel free to type!</h1>
<blockquote>{userText}</blockquote>
</div>
);
Personally I don't like the solution, feels anti-react
and I think the first method is good enough and is designed to be used that way.
edited 3 hours ago
answered 4 hours ago
varun agarwalvarun agarwal
96629
96629
Do you mind to include some code to demonstrate how to achieve my objective in second method?
– Isaac
4 hours ago
add a comment |
Do you mind to include some code to demonstrate how to achieve my objective in second method?
– Isaac
4 hours ago
Do you mind to include some code to demonstrate how to achieve my objective in second method?
– Isaac
4 hours ago
Do you mind to include some code to demonstrate how to achieve my objective in second method?
– Isaac
4 hours ago
add a comment |
try this, it works same as your original code:
useEffect(() => {
function handlekeydownEvent(event) {
const { key, keyCode } = event;
if (keyCode === 32 || (keyCode >= 65 && keyCode <= 90)) {
setUserText(`${userText}${key}`);
}
}
document.addEventListener('keyup', handlekeydownEvent)
return () => {
document.removeEventListener('keyup', handlekeydownEvent)
}
}, [userText])
because in your useEffect()
method, it depends on the userText
variable but you don't put it inside the second argument, else the userText
will always be bound to the initial value ''
with argument []
.
you don't need to do like this, just want to let you know why your second solution doesn't work.
By adding[userText]
is exactly the same as without second argument, right? Reason is I only haveuserText
in the above example, and without second argument simply means re-rerender on every props/state changes, I don't see how it answer my question. **P/S: ** I'm not the downvoter, thanks for your answer anyway
– Isaac
4 hours ago
hey @Isaac , yep, it is same as without second argument, I just want to let you know why your second solution doesn't work, because your second solutionuseEffect()
depend on theuserText
variable but you didn't put inside the second arguments.
– Spark.Bao
3 hours ago
But by adding in[userText]
, it also means register and deregister the event on every re-render right?
– Isaac
3 hours ago
exactly! that why I say it is same with your first solution.
– Spark.Bao
3 hours ago
1
got what you mean, if you really want to register it only one time in this example, then you need to useuseRef
, just as @Maaz Syed Adeeb 's answer.
– Spark.Bao
3 hours ago
|
show 4 more comments
try this, it works same as your original code:
useEffect(() => {
function handlekeydownEvent(event) {
const { key, keyCode } = event;
if (keyCode === 32 || (keyCode >= 65 && keyCode <= 90)) {
setUserText(`${userText}${key}`);
}
}
document.addEventListener('keyup', handlekeydownEvent)
return () => {
document.removeEventListener('keyup', handlekeydownEvent)
}
}, [userText])
because in your useEffect()
method, it depends on the userText
variable but you don't put it inside the second argument, else the userText
will always be bound to the initial value ''
with argument []
.
you don't need to do like this, just want to let you know why your second solution doesn't work.
By adding[userText]
is exactly the same as without second argument, right? Reason is I only haveuserText
in the above example, and without second argument simply means re-rerender on every props/state changes, I don't see how it answer my question. **P/S: ** I'm not the downvoter, thanks for your answer anyway
– Isaac
4 hours ago
hey @Isaac , yep, it is same as without second argument, I just want to let you know why your second solution doesn't work, because your second solutionuseEffect()
depend on theuserText
variable but you didn't put inside the second arguments.
– Spark.Bao
3 hours ago
But by adding in[userText]
, it also means register and deregister the event on every re-render right?
– Isaac
3 hours ago
exactly! that why I say it is same with your first solution.
– Spark.Bao
3 hours ago
1
got what you mean, if you really want to register it only one time in this example, then you need to useuseRef
, just as @Maaz Syed Adeeb 's answer.
– Spark.Bao
3 hours ago
|
show 4 more comments
try this, it works same as your original code:
useEffect(() => {
function handlekeydownEvent(event) {
const { key, keyCode } = event;
if (keyCode === 32 || (keyCode >= 65 && keyCode <= 90)) {
setUserText(`${userText}${key}`);
}
}
document.addEventListener('keyup', handlekeydownEvent)
return () => {
document.removeEventListener('keyup', handlekeydownEvent)
}
}, [userText])
because in your useEffect()
method, it depends on the userText
variable but you don't put it inside the second argument, else the userText
will always be bound to the initial value ''
with argument []
.
you don't need to do like this, just want to let you know why your second solution doesn't work.
try this, it works same as your original code:
useEffect(() => {
function handlekeydownEvent(event) {
const { key, keyCode } = event;
if (keyCode === 32 || (keyCode >= 65 && keyCode <= 90)) {
setUserText(`${userText}${key}`);
}
}
document.addEventListener('keyup', handlekeydownEvent)
return () => {
document.removeEventListener('keyup', handlekeydownEvent)
}
}, [userText])
because in your useEffect()
method, it depends on the userText
variable but you don't put it inside the second argument, else the userText
will always be bound to the initial value ''
with argument []
.
you don't need to do like this, just want to let you know why your second solution doesn't work.
edited 3 hours ago
answered 4 hours ago
Spark.BaoSpark.Bao
2,6411730
2,6411730
By adding[userText]
is exactly the same as without second argument, right? Reason is I only haveuserText
in the above example, and without second argument simply means re-rerender on every props/state changes, I don't see how it answer my question. **P/S: ** I'm not the downvoter, thanks for your answer anyway
– Isaac
4 hours ago
hey @Isaac , yep, it is same as without second argument, I just want to let you know why your second solution doesn't work, because your second solutionuseEffect()
depend on theuserText
variable but you didn't put inside the second arguments.
– Spark.Bao
3 hours ago
But by adding in[userText]
, it also means register and deregister the event on every re-render right?
– Isaac
3 hours ago
exactly! that why I say it is same with your first solution.
– Spark.Bao
3 hours ago
1
got what you mean, if you really want to register it only one time in this example, then you need to useuseRef
, just as @Maaz Syed Adeeb 's answer.
– Spark.Bao
3 hours ago
|
show 4 more comments
By adding[userText]
is exactly the same as without second argument, right? Reason is I only haveuserText
in the above example, and without second argument simply means re-rerender on every props/state changes, I don't see how it answer my question. **P/S: ** I'm not the downvoter, thanks for your answer anyway
– Isaac
4 hours ago
hey @Isaac , yep, it is same as without second argument, I just want to let you know why your second solution doesn't work, because your second solutionuseEffect()
depend on theuserText
variable but you didn't put inside the second arguments.
– Spark.Bao
3 hours ago
But by adding in[userText]
, it also means register and deregister the event on every re-render right?
– Isaac
3 hours ago
exactly! that why I say it is same with your first solution.
– Spark.Bao
3 hours ago
1
got what you mean, if you really want to register it only one time in this example, then you need to useuseRef
, just as @Maaz Syed Adeeb 's answer.
– Spark.Bao
3 hours ago
By adding
[userText]
is exactly the same as without second argument, right? Reason is I only have userText
in the above example, and without second argument simply means re-rerender on every props/state changes, I don't see how it answer my question. **P/S: ** I'm not the downvoter, thanks for your answer anyway– Isaac
4 hours ago
By adding
[userText]
is exactly the same as without second argument, right? Reason is I only have userText
in the above example, and without second argument simply means re-rerender on every props/state changes, I don't see how it answer my question. **P/S: ** I'm not the downvoter, thanks for your answer anyway– Isaac
4 hours ago
hey @Isaac , yep, it is same as without second argument, I just want to let you know why your second solution doesn't work, because your second solution
useEffect()
depend on the userText
variable but you didn't put inside the second arguments.– Spark.Bao
3 hours ago
hey @Isaac , yep, it is same as without second argument, I just want to let you know why your second solution doesn't work, because your second solution
useEffect()
depend on the userText
variable but you didn't put inside the second arguments.– Spark.Bao
3 hours ago
But by adding in
[userText]
, it also means register and deregister the event on every re-render right?– Isaac
3 hours ago
But by adding in
[userText]
, it also means register and deregister the event on every re-render right?– Isaac
3 hours ago
exactly! that why I say it is same with your first solution.
– Spark.Bao
3 hours ago
exactly! that why I say it is same with your first solution.
– Spark.Bao
3 hours ago
1
1
got what you mean, if you really want to register it only one time in this example, then you need to use
useRef
, just as @Maaz Syed Adeeb 's answer.– Spark.Bao
3 hours ago
got what you mean, if you really want to register it only one time in this example, then you need to use
useRef
, just as @Maaz Syed Adeeb 's answer.– Spark.Bao
3 hours ago
|
show 4 more comments
you dont have access to the changed useText state. you can comapre it to the prevState. store the state in a variable e.g.: state like so:
const [userText, setUserText] = useState('');
let state = ''
const handleUserKeyPress = event => {
const { key, keyCode } = event;
if (keyCode === 32 || (keyCode >= 65 && keyCode <= 90)) {
state += `${key}`
setUserText(state);
}
};
useEffect(() => {
window.addEventListener('keydown', handleUserKeyPress);
return () => {
window.removeEventListener('keydown', handleUserKeyPress);
};
}, []);
return (
<div>
<h1>Feel free to type!</h1>
<blockquote>{userText}</blockquote>
</div>
);
add a comment |
you dont have access to the changed useText state. you can comapre it to the prevState. store the state in a variable e.g.: state like so:
const [userText, setUserText] = useState('');
let state = ''
const handleUserKeyPress = event => {
const { key, keyCode } = event;
if (keyCode === 32 || (keyCode >= 65 && keyCode <= 90)) {
state += `${key}`
setUserText(state);
}
};
useEffect(() => {
window.addEventListener('keydown', handleUserKeyPress);
return () => {
window.removeEventListener('keydown', handleUserKeyPress);
};
}, []);
return (
<div>
<h1>Feel free to type!</h1>
<blockquote>{userText}</blockquote>
</div>
);
add a comment |
you dont have access to the changed useText state. you can comapre it to the prevState. store the state in a variable e.g.: state like so:
const [userText, setUserText] = useState('');
let state = ''
const handleUserKeyPress = event => {
const { key, keyCode } = event;
if (keyCode === 32 || (keyCode >= 65 && keyCode <= 90)) {
state += `${key}`
setUserText(state);
}
};
useEffect(() => {
window.addEventListener('keydown', handleUserKeyPress);
return () => {
window.removeEventListener('keydown', handleUserKeyPress);
};
}, []);
return (
<div>
<h1>Feel free to type!</h1>
<blockquote>{userText}</blockquote>
</div>
);
you dont have access to the changed useText state. you can comapre it to the prevState. store the state in a variable e.g.: state like so:
const [userText, setUserText] = useState('');
let state = ''
const handleUserKeyPress = event => {
const { key, keyCode } = event;
if (keyCode === 32 || (keyCode >= 65 && keyCode <= 90)) {
state += `${key}`
setUserText(state);
}
};
useEffect(() => {
window.addEventListener('keydown', handleUserKeyPress);
return () => {
window.removeEventListener('keydown', handleUserKeyPress);
};
}, []);
return (
<div>
<h1>Feel free to type!</h1>
<blockquote>{userText}</blockquote>
</div>
);
answered 3 hours ago
di3di3
491210
491210
add a comment |
add a comment |
For your use case, useEffect
needs a dependency array to track changes and based on the dependency it can determine whether to re-render or not. It is always advised to pass a dependency array to useEffect
. Kindly see the code below:
I have introduced useCallback
hook.
const { useCallback, useState, useEffect } = React;
function App() {
const [userText, setUserText] = useState('');
const handleUserKeyPress = useCallback(event => {
const { key, keyCode } = event;
if (keyCode === 32 || (keyCode >= 65 && keyCode <= 90)) {
setUserText(`${userText}${key}`);
}
}, [userText]);
useEffect(() => {
window.addEventListener('keydown', handleUserKeyPress);
return () => {
window.removeEventListener('keydown', handleUserKeyPress);
};
}, [handleUserKeyPress]);
return (
<div>
<blockquote>{userText}</blockquote>
</div>
);
}
I've tried your solution, but it's exactly the same as[userText]
or without second argument. Basically we put aconsole.log
insideuseEffect
, we will see that the logging is firing every re-render, which also means,addEventListender
is running every re-render
– Isaac
3 hours ago
I want to believe that is an expected behaviour. I updated my answer.
– John Kennedy
3 hours ago
On your sandbox, you've put a statementconsole.log('>');
withinuseEffect
hooks, and by using your updated code, it's still logging everytime, which also means the events are still registering on every re-render
– Isaac
3 hours ago
1
but because ofreturn () => {window.removeEventListener('keydown', handleUserKeyPress)}
, on every re-render, the component will register and deregister
– Isaac
2 hours ago
1
Exactly the behaviour that I wished for, but you can observe it @ codesandbox.io/s/n5j7qy051j
– Isaac
2 hours ago
|
show 2 more comments
For your use case, useEffect
needs a dependency array to track changes and based on the dependency it can determine whether to re-render or not. It is always advised to pass a dependency array to useEffect
. Kindly see the code below:
I have introduced useCallback
hook.
const { useCallback, useState, useEffect } = React;
function App() {
const [userText, setUserText] = useState('');
const handleUserKeyPress = useCallback(event => {
const { key, keyCode } = event;
if (keyCode === 32 || (keyCode >= 65 && keyCode <= 90)) {
setUserText(`${userText}${key}`);
}
}, [userText]);
useEffect(() => {
window.addEventListener('keydown', handleUserKeyPress);
return () => {
window.removeEventListener('keydown', handleUserKeyPress);
};
}, [handleUserKeyPress]);
return (
<div>
<blockquote>{userText}</blockquote>
</div>
);
}
I've tried your solution, but it's exactly the same as[userText]
or without second argument. Basically we put aconsole.log
insideuseEffect
, we will see that the logging is firing every re-render, which also means,addEventListender
is running every re-render
– Isaac
3 hours ago
I want to believe that is an expected behaviour. I updated my answer.
– John Kennedy
3 hours ago
On your sandbox, you've put a statementconsole.log('>');
withinuseEffect
hooks, and by using your updated code, it's still logging everytime, which also means the events are still registering on every re-render
– Isaac
3 hours ago
1
but because ofreturn () => {window.removeEventListener('keydown', handleUserKeyPress)}
, on every re-render, the component will register and deregister
– Isaac
2 hours ago
1
Exactly the behaviour that I wished for, but you can observe it @ codesandbox.io/s/n5j7qy051j
– Isaac
2 hours ago
|
show 2 more comments
For your use case, useEffect
needs a dependency array to track changes and based on the dependency it can determine whether to re-render or not. It is always advised to pass a dependency array to useEffect
. Kindly see the code below:
I have introduced useCallback
hook.
const { useCallback, useState, useEffect } = React;
function App() {
const [userText, setUserText] = useState('');
const handleUserKeyPress = useCallback(event => {
const { key, keyCode } = event;
if (keyCode === 32 || (keyCode >= 65 && keyCode <= 90)) {
setUserText(`${userText}${key}`);
}
}, [userText]);
useEffect(() => {
window.addEventListener('keydown', handleUserKeyPress);
return () => {
window.removeEventListener('keydown', handleUserKeyPress);
};
}, [handleUserKeyPress]);
return (
<div>
<blockquote>{userText}</blockquote>
</div>
);
}
For your use case, useEffect
needs a dependency array to track changes and based on the dependency it can determine whether to re-render or not. It is always advised to pass a dependency array to useEffect
. Kindly see the code below:
I have introduced useCallback
hook.
const { useCallback, useState, useEffect } = React;
function App() {
const [userText, setUserText] = useState('');
const handleUserKeyPress = useCallback(event => {
const { key, keyCode } = event;
if (keyCode === 32 || (keyCode >= 65 && keyCode <= 90)) {
setUserText(`${userText}${key}`);
}
}, [userText]);
useEffect(() => {
window.addEventListener('keydown', handleUserKeyPress);
return () => {
window.removeEventListener('keydown', handleUserKeyPress);
};
}, [handleUserKeyPress]);
return (
<div>
<blockquote>{userText}</blockquote>
</div>
);
}
edited 3 hours ago
answered 3 hours ago
John KennedyJohn Kennedy
3,01021227
3,01021227
I've tried your solution, but it's exactly the same as[userText]
or without second argument. Basically we put aconsole.log
insideuseEffect
, we will see that the logging is firing every re-render, which also means,addEventListender
is running every re-render
– Isaac
3 hours ago
I want to believe that is an expected behaviour. I updated my answer.
– John Kennedy
3 hours ago
On your sandbox, you've put a statementconsole.log('>');
withinuseEffect
hooks, and by using your updated code, it's still logging everytime, which also means the events are still registering on every re-render
– Isaac
3 hours ago
1
but because ofreturn () => {window.removeEventListener('keydown', handleUserKeyPress)}
, on every re-render, the component will register and deregister
– Isaac
2 hours ago
1
Exactly the behaviour that I wished for, but you can observe it @ codesandbox.io/s/n5j7qy051j
– Isaac
2 hours ago
|
show 2 more comments
I've tried your solution, but it's exactly the same as[userText]
or without second argument. Basically we put aconsole.log
insideuseEffect
, we will see that the logging is firing every re-render, which also means,addEventListender
is running every re-render
– Isaac
3 hours ago
I want to believe that is an expected behaviour. I updated my answer.
– John Kennedy
3 hours ago
On your sandbox, you've put a statementconsole.log('>');
withinuseEffect
hooks, and by using your updated code, it's still logging everytime, which also means the events are still registering on every re-render
– Isaac
3 hours ago
1
but because ofreturn () => {window.removeEventListener('keydown', handleUserKeyPress)}
, on every re-render, the component will register and deregister
– Isaac
2 hours ago
1
Exactly the behaviour that I wished for, but you can observe it @ codesandbox.io/s/n5j7qy051j
– Isaac
2 hours ago
I've tried your solution, but it's exactly the same as
[userText]
or without second argument. Basically we put a console.log
inside useEffect
, we will see that the logging is firing every re-render, which also means, addEventListender
is running every re-render– Isaac
3 hours ago
I've tried your solution, but it's exactly the same as
[userText]
or without second argument. Basically we put a console.log
inside useEffect
, we will see that the logging is firing every re-render, which also means, addEventListender
is running every re-render– Isaac
3 hours ago
I want to believe that is an expected behaviour. I updated my answer.
– John Kennedy
3 hours ago
I want to believe that is an expected behaviour. I updated my answer.
– John Kennedy
3 hours ago
On your sandbox, you've put a statement
console.log('>');
within useEffect
hooks, and by using your updated code, it's still logging everytime, which also means the events are still registering on every re-render– Isaac
3 hours ago
On your sandbox, you've put a statement
console.log('>');
within useEffect
hooks, and by using your updated code, it's still logging everytime, which also means the events are still registering on every re-render– Isaac
3 hours ago
1
1
but because of
return () => {window.removeEventListener('keydown', handleUserKeyPress)}
, on every re-render, the component will register and deregister– Isaac
2 hours ago
but because of
return () => {window.removeEventListener('keydown', handleUserKeyPress)}
, on every re-render, the component will register and deregister– Isaac
2 hours ago
1
1
Exactly the behaviour that I wished for, but you can observe it @ codesandbox.io/s/n5j7qy051j
– Isaac
2 hours ago
Exactly the behaviour that I wished for, but you can observe it @ codesandbox.io/s/n5j7qy051j
– Isaac
2 hours ago
|
show 2 more comments
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.
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55565444%2fhow-to-register-event-with-useeffect-hooks%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
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