The function makes the dependencies of useEffect Hook

Viewed 43471

I have a function that sets my useState when on click, everything works fine but I am getting a warning everytime:

 Line 22:  The 'handleClickOpen' function makes the dependencies of useEffect Hook (at line 20) change on every render. To fix this, wrap the 'handleClickOpen' definition into its own useCallback() Hook  react-hooks/exhaustive-deps

this is my code:

  useEffect(() => {
    axios.get("/api/getBlacklist/").then(data => setBlacklistItems(data.data));

    // eslint-disable-next-line
  }, [handleClickOpen]);

  function handleClickOpen() {
    setOpen(true);
  }

I have tried to replace handleClickOpen in useEffect with just setOpen(true), but then my page crashes because of too many re-renders.

How to deal with this situation?

1 Answers

Every render it will create new handleClickOpen function. You can memoize it by useCallback

import { useCallback } from 'react'

const handleClickOpen = useCallback(() => {
  setOpen(true)
}, [])
Related