I have 2 outside events, input and keydown for an input element, when input fired, it will call setInput in React component. When keydown event for arrowDown fired, ideally the input value should be the one set inside handleInput, but it's empty, do I miss something?
const SearchBox : React.FunctionComponent<ISearchProps> = React.memo((props: ISearchProps) => {
const [input, setInput] = React.useState({value: '', redirect: false});
useEffect(() => {
const container = document.querySelector('.xxx');
container.addEventListener('input', handleInput);
container.addEventListener('keydown', handleKeyboardEvent);
}, []);
const handleInput = (e) => {
setInput({value: e.currentTarget.value, redirect: false});
}
const handleKeyboardEvent = (e) => {
switch (e.key) {
case 'ArrowDown':
console.log(input);
setActiveSuggestionIndex(activeSuggestionIndex === suggestions.length - 1 ? 0 : activeSuggestionIndex + 1);
e.preventDefault();
break;
default:
break;
}
}
}
This is an issue of stale enclosures of state in a callback function. The initial input state value of { value: '', redirect: false } is closed over in the copy of handleKeyboardEvent from the initial render cycle. It will never update.
useEffect to cache a copy of valueUse a React ref and an additional useEffect hook to cache a value to be accessed asynchronously in the callback.
const [input, setInput] = React.useState({ value: '', redirect: false });
const inputRef = React.useRef(input); // <-- state cache
useEffect(() => {
const container = document.querySelector('.xxx');
container.addEventListener('input', handleInput);
container.addEventListener('keydown', handleKeyboardEvent);
return () => {
container.removeEventListener('input', handleInput);
container.removeEventListener('keydown', handleKeyboardEvent);
};
}, []);
useEffect(() => {
inputRef.current = input; // <-- update state cache value
}, [input]);
const handleInput = (e) => {
setInput({ value: e.currentTarget.value, redirect: false });
};
const handleKeyboardEvent = (e) => {
switch (e.key) {
case 'ArrowDown':
console.log(inputRef); // <-- read current state cache value
setActiveSuggestionIndex(activeSuggestionIndex =>
activeSuggestionIndex === suggestions.length - 1
? 0
: activeSuggestionIndex + 1
);
e.preventDefault();
break;
default:
break;
}
};
useEffect with dependency and cleanup functionSince you should also already be returning a cleanup function from the useEffect to remove the event listeners when unmounting, add the input state to the dependency array (and any other missing dependencies the linter may complain about) so that when the input state updates, the current state value is re-enclosed in callback scope.
useEffect(() => {
const handleInput = (e) => {
setInput({ value: e.currentTarget.value, redirect: false });
};
const handleKeyboardEvent = (e) => {
switch (e.key) {
case 'ArrowDown':
console.log(input);
setActiveSuggestionIndex(activeSuggestionIndex =>
activeSuggestionIndex === suggestions.length - 1
? 0
: activeSuggestionIndex + 1
);
e.preventDefault();
break;
default:
break;
}
};
const container = document.querySelector('.xxx');
container.addEventListener('input', handleInput);
container.addEventListener('keydown', handleKeyboardEvent);
return () => {
container.removeEventListener('input', handleInput);
container.removeEventListener('keydown', handleKeyboardEvent);
};
}, [input]);