https://codesandbox.io/s/suspicious-chebyshev-vy4mf2
I have a useReducer hook and useEffect with a keydown
event handler. The issue is that on each re-render resulting from handling the keyboard button press, the component function re-runs the function obtaining initial state.
The visible incorrect result is the random number logged in console on each render (I expect no logging). In other words, the goal here is to stop getInitialState function running on every render.
import { useEffect, useReducer } from "react";
import "./styles.css";
interface IAction {
type: string;
payload: string;
}
export default function App() {
const reducer = (state: string, action: IAction) => {
switch (action.type) {
case "KEYDOWN":
return action.payload;
default:
return state;
}
};
const getInitialState = () => {
const rand = Math.random().toString();
console.log(rand);
return rand;
};
const [state, dispatch] = useReducer(reducer, getInitialState());
const keyDownHandler = (e: KeyboardEvent): void => {
dispatch({
type: "KEYDOWN",
payload: e.key
});
};
useEffect(() => {
document.addEventListener("keydown", keyDownHandler);
return () => document.removeEventListener("keydown", keyDownHandler);
}, [state, dispatch]);
return <div className="App">{state}</div>;
}