React state update properly with keyboard event

2 weeks ago 20
ARTICLE AD BOX

I have an interesting scenario, I have a react component which maintains a state value and I want to concatenate the next character to it when either the key or an HTML element is pressed.

The problem: When the HTML element is pressed the value is concatenated just fine however, when a key is pressed the value overrides.

I have checked the value with useEffect and it updates but when another key is pressed the value is empty.

import { useCallback, useEffect, useState } from "react"; export function ValueTest() { const [value, setValue] = useState<string>(""); const keypress = (v: string) => { setValue(value + v); }; const keyUpHandler = useCallback((event) => { event.preventDefault(); keypress(event.key); }, []); useEffect(() => { document.addEventListener("keyup", keyUpHandler); return () => { document.removeEventListener("keyup", keyUpHandler, false); }; }, [keyUpHandler]); useEffect(() => { console.log(value); }, [value]); return ( <div> <div style={{ width: "20px", height: "20px" }} onClick={() => keypress("1")} > 1 </div> {value} </div> ); }
Read Entire Article