1

Here is my code. I'm just displaying offsetX and offsetY in React component. Also dispatching it to Redux store by using addToStore(). I'm not sure what values should I add to deps array. I added dispatch, but there are offsetX and offsetY states there.

function PageMouseMove () {
  const dispatch = useDispatch()

  const [offsetX, setOffsetX] = useState(0)
  const [offsetY, setOffsetY] = useState(0)
  useEffect(() => {
    const mouseMove = ({ offsetX, offsetY }) => {
      addToStore({ offsetX, offsetY })(dispatch)
      setOffsetX(offsetX)
      setOffsetY(offsetY)
    }
    window.addEventListener('mousemove', mouseMove)
    return () => {
      window.removeEventListener('mousemove', mouseMove)
    }
  }, [dispatch])

  return (
    <div>
      X - {offsetX}, Y - {offsetY}
    </div>
  )
}
1
  • 1
    Your dependencies are the list of variables that will trigger the useEffect. If you want to trigger the useEffect when offsetX or offsetY changes, you should add them to the array Commented Jul 31, 2020 at 12:27

1 Answer 1

2

As @Nicolai Mons Mogensen mentions in the comments, the dependencies that you add to the useEffect(fn,[deps]) method are the variables that will trigger the function.

I would add that the useEffect function will get triggered when the variables change.

Your function looks correct, but is missing a closing curly, which I assume is a copy-paste error.

Personally, I would change the variable names in the hook to avoid confusion. Like so:

function PageMouseMove() {
  const dispatch = useDispatch();

  const [offsetX, setOffsetX] = useState(0);
  const [offsetY, setOffsetY] = useState(0);

  useEffect(() => {
    const mouseMove = ({ offX, offY }) => {
      addToStore({ offsetX: offX, offsetY: offY })(dispatch);
      setOffsetX(offX);
      setOffsetY(offY);
    };
    window.addEventListener('mousemove', mouseMove);

    return () => {
      window.removeEventListener('mousemove', mouseMove);
    };
  }, [dispatch]);
}
Sign up to request clarification or add additional context in comments.

1 Comment

Ok great, it works. I edited the code so full component can be seen now. Thanks!

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.