67

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?

sanna
  • 1,398
  • 5
  • 16
  • 24
  • 2
    I found this article very helpful for solving this issue https://typeofnan.dev/fix-function-makes-the-dependencies-of-useEffect-hook-change-on-every-render-warning-in-react/ – Yvonne Aburrow Jan 21 '22 at 13:44

1 Answers1

128

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

import { useCallback } from 'react'

const handleClickOpen = useCallback(() => {
  setOpen(true)
}, [])
jbranchaud
  • 5,909
  • 9
  • 45
  • 70
Giang Le
  • 6,446
  • 4
  • 23
  • 26
  • 15
    Why would every render create a new `handleClickOpen` function? – darKnight Feb 18 '21 at 11:23
  • 2
    That's how javascript and thus react works, every renders functions are unique. You can read a bit about it here (step 2): https://dmitripavlutin.com/dont-overuse-react-usecallback/ – plebksig May 21 '21 at 10:52
  • try using whyDidYouRender library in you project and you will get these warnings in console. https://github.com/welldone-software/why-did-you-render Basically while rendering it checks for previous handleClickOpen & new created handleClickOpen function. Even thought the code content will look same their references will not be right and thus falsify conditon. https://www.youtube.com/watch?v=ZvbzSrg0afE&list=PLlasXeu85E9cQ32gLCvAvr9vNaUccPVNP&index=3 https://www.youtube.com/watch?v=iLWTnMzWtj4&list=PLlasXeu85E9cQ32gLCvAvr9vNaUccPVNP&index=4 – Sunny Aug 31 '21 at 06:05
  • If you are triggering the `react-hooks/exhaustive-deps` lint rule, then `useCallback` does not help to fix it (it just gives the same warning), in which this answer helps instead: https://stackoverflow.com/a/55854902/795690 – MikeBeaton Dec 19 '22 at 16:23