The function makes the dependencies of useEffect Hook

Reactjs

Reactjs Problem Overview


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?

Reactjs Solutions


Solution 1 - Reactjs

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

import { useCallback } from 'react'

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionsannaView Question on Stackoverflow
Solution 1 - ReactjsGiang LeView Answer on Stackoverflow