Guy
Guy

Reputation: 13306

A variable from useState within a hook callback is closured

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

Answers (1)

Ori Drori
Ori Drori

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

Related Questions