Reputation: 13306
I use useKey to respond to Enter.
const [isFocused, setIsFocused] = useState(false);
useKey("Enter", ev => {
console.log("ev, isFocused -> ", ev, isFocused);
});
However, the isFocused value printed is always false even if it was changed.
How can one prevent a useState variable from being frozen to the initial value?
Upvotes: 1
Views: 65
Reputation: 191976
The useKey
hook supports dependencies (4th param):
const useKey = (key: KeyFilter, fn: Handler = noop, opts: UseKeyOptions = {}, deps: DependencyList = [key])
Wrap the event handler with useCallback
and set it's dependancy to be isFocused
, and then pass the event handler as a dependancy to useKey
. If isFocused
changes, eventHandler
changes, and useKey
will update accordingly:
const eventHandler = useCallback(ev => {
console.log("ev, isFocused -> ", ev, isFocused);
}, [isFocused])
useKey("Enter", eventHandler, {}, [eventHandler]);
Upvotes: 3