In the code below, a keypress event detector is implemented through useEffect
which attempts to update index
through the useReducer
function. However, the console.log
output doesn't seem to show that the update works even though the button
component's value updates.
On the other hand, when the button is clicked, the index
variable seems to update as indicated by the console.log
and the content of the button
also updates as expected.
Why is there such a disparity and - if I needed to access the updated index
variable after a keypress, how could I go about doing it?
The code is below:
const { useEffect, useReducer } = React;
const indexReducer = (state, action) => {
if (action === "decrease") {
return state-1
} else if (action === "increase") {
return state+1
} else if (action === "reset") {
return 0
}
}
function App() {
const [counter, setCounter] = useReducer(indexReducer, 0)
const incrementCounter = () => {
console.log(counter)
setCounter("increase")
}
useEffect(() => {
document.addEventListener("keydown", incrementCounter, false);
return () => {
document.removeEventListener("keydown", incrementCounter, false);
};
}, []);
return (
<div className="App">
<button onClick={incrementCounter}>{"COUNT: " + counter}</button>
</div>
);
}
ReactDOM.render(<App />, document.body);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.0/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.0/umd/react-dom.production.min.js"></script>