0

I'm moving over to functional components from class components and having trouble handling this scenario. This component's state can be updated by 2 different event listeners: key down or mouseover. I want to trigger a callback after the state is updated ONLY if updated by key down. Any way to do this?

const handleMouseOver = e => {
  setSelection(e.target.value)
}

const handleDownArrowKeyDown = () => {
   ...
   setSelection(selection + 1)
}

useEffect(() => {
   // Only execute below if selection state was updated by handleDownArrowKeyDown
   ...
}, [selection])

1 Answer 1

1

Put that code inside handleDownArrowKeyDown instead - accounting for the new selection number.

const handleMouseOver = e => {
    setSelection(e.target.value)
}

const handleDownArrowKeyDown = () => {
    setSelection(newSelection)
    const newSelection = selection + 1;
    // stuff that relies on newSelection
}
Sign up to request clarification or add additional context in comments.

2 Comments

No guarantee that will execute after the state has been set.
Indeed, it definitely won't execute after the state has been set - rather, it'll definitely execute before the state has been set, which is why you need // stuff that relies on newSelection rather than an effect hook.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.