useEffect(() => {
console.log("change in focus")
}, [DEPENDENCY]);
I want a DEPENDENCY
that changes when the focus changes in the document; an example would be when a user clicks on or off an input. I tried document.activeElement
but it didn’t work.
2
Answers
useEffect
dependency arrays are only useful if your component is already rendering. You will need to write code that causes it to rerender. To be notified when focus changes you can use thefocusin
event. And if you want to render when this happens, you can set state.For example:
You may also want to listen to the
focusout
event.You can’t directly use
document.activeElement
as a dependency inuseEffect
becauseuseEffect
dependencies must be values that can change and trigger a re-render, not side-effect operations like event handling.