๐Ÿ‘ฉ‍๐Ÿ’ป/React

[React.js Hooks] React Hook useEffect has a missing dependency: 'dispatch'. Either include it or remove the dependency array react-hooks/exhaustive-deps issue

ํ•œ๋‚˜ 2021. 3. 9. 04:02

๋ฌธ์ œ ์ƒํ™ฉ

error occured!

useEffect๋ฅผ ์“ฐ๋ฉด์„œ ์ž์ฃผ ๋งŒ๋‚˜๋Š” ์—๋Ÿฌ ํ•ธ๋“ค๋ง์„ ํ•ด๋ณด์ž.

๋ฌธ์ œ ์›์ธ ๋ฐ ํ•ด๊ฒฐ

useEffect๋Š” ํด๋ž˜์Šค ์ปดํฌ๋„ŒํŠธ์—์„œ componentDidMount()์™€ componentDidUpdate() ๋ผ์ดํ”„ ์‚ฌ์ดํด ๋ฉ”์†Œ๋“œ ๋‘ ๊ฐœ๋ฅผ ํ•ฉ์นœ ์—ญํ• ์„ ํ•œ๋‹ค๊ณ  ๋ฐฐ์› ๋‹ค. ๋”ฐ๋ผ์„œ, useEffect ํ•จ์ˆ˜์˜ ๋‘ ๋ฒˆ์งธ ์ธ์ž์— ๋นˆ ๋ฐฐ์—ด์„ ๋„ฃ๊ฑฐ๋‚˜, ์—…๋ฐ์ดํŠธ ํ•˜๊ณ ์ž ํ•˜๋Š” state๋ฅผ ๋„ฃ์–ด์ฃผ์–ด ๋ Œ๋”๋ง์˜ ํšŸ์ˆ˜๋ฅผ ์ œํ•œํ•ด์ฃผ์–ด์•ผ ํ•˜๋Š”๋ฐ, ์œ„ ์—๋Ÿฌ๋Š” ํ•ด๋‹น state๊ฐ€ ๋น ์กŒ๊ฑฐ๋‚˜, ์ž˜๋ชป ๋“ค์–ด๊ฐ”๊ฑฐ๋‚˜ ํ•ด์„œ ๋‚˜์˜ค๋Š” ์—๋Ÿฌ์ด๋‹ค.

๋ฌธ์ œ์˜ ์›์ธ์ด ๋œ ์ฝ”๋“œ๋Š” App.js์™€ Snackbar.js ์ปดํฌ๋„ŒํŠธ์—์„œ์˜€๋‹ค. App.js์—์„œ๋Š” Redux๋ฅผ ํ†ตํ•ด ๋ฐ˜์‘ํ˜• ์ปดํฌ๋„ŒํŠธ ๋นŒ๋”ฉ์„ ์œ„ํ•ด size๋ฅผ store์— ๋“ฑ๋กํ•ด์ฃผ๊ธฐ ์œ„ํ•ด ๋ฆฌํŒฉํ† ๋ง์„ ํ•˜๋‹ค๊ฐ€ ์ƒ๊ฒผ๋‹ค.


function App() {
  const dispatch = useDispatch();
  let [currentSize, setCurrentSize] = useState('')

  useEffect(() => {
    dispatch(changeSize(currentSize))
  }, [dispatch, currentSize])

  return (  
      <Grommet id='container' theme={theme}>
        <ResponsiveContext.Consumer>{
          size => { setCurrentSize(size)
            return (
              <>
                <Box>
                  <Header channel={myMedia} theme={theme} />
                </Box>
                <Body channel={myMedia} />
                <Footer channel={myMedia} />
              </>
            )
          } 
        }
        </ResponsiveContext.Consumer>
      </Grommet>
  );
}

Grommet์ด ์ œ๊ณตํ•˜๋Š” <ResponsiveContext.Consumer>๋Š” String์„ ํ†ตํ•ด size๋ฅผ ๋ฐ˜ํ™˜ํ•œ๋‹ค. ์ปค์Šคํ…€ theme์„ ํ†ตํ•ด์„œ ์„ธ๋ฐ€ํ•˜๊ฒŒ breakpoints๋ฅผ ์กฐ์ •ํ•  ์ˆ˜ ์žˆ์–ด์„œ, ๋ชจ๋“  ๋ฐ˜์‘ํ˜• ์‚ฌ์ด์ฆˆ ๋ฐ์ดํ„ฐ๋Š” ์ด๊ณณ์—์„œ ๋ฐ›์•„ ์‚ฌ์šฉ ์ค‘์ด๋‹ค. ํ•˜์ง€๋งŒ nested components๋ฅผ ๊ณ„์† props๋กœ๋งŒ ์ „๋‹ฌํ•˜๋Š” ๊ฒƒ์— ํ•œ๊ณ„๋ฅผ ๋Š๊ปด์„œ redux๋ฅผ ๋„์ž…ํ–ˆ๋‹ค. ๋ฌธ์ œ๋Š” <ResponsiveContext.Consumer> ์ปดํฌ๋„ŒํŠธ๋กœ๋ถ€ํ„ฐ size๋ฅผ dispatch ํ•ด์•ผ ํ•˜๋Š”๋ฐ,

  useEffect(() => {
    dispatch(changeSize(currentSize))
  }, [currentSize])

dispatch๋ฅผ ์ ์šฉํ•˜์ง€๋Š” ์•Š๊ณ , currentSize๋งŒ ๊ฐ์ง€ํ•˜๋„๋ก ํ•ด๋‘ฌ์„œ ์—๋Ÿฌ๊ฐ€ ๋ฐœ์ƒํ–ˆ๋‹ค.
๋ฐฐ์—ด์— dispatch๋ฅผ ํ•จ๊ป˜ ๋„ฃ์–ด์„œ ํ•ด๊ฒฐํ•  ์ˆ˜ ์žˆ์—ˆ๋‹ค. ์ด๋Ÿฐ ์—๋Ÿฌ๋Š” useEffect ๋‚ด๋ถ€์— ํ•จ์ˆ˜๋ฅผ ์ •์˜ํ•œ ๊ฒฝ์šฐ ๋ฐœ์ƒํ•  ์ˆ˜ ์žˆ๋‹ค.

// snackbar.js
 useEffect(() => {
        if (props.barStatus === '') {
            setOpen(false);
        } else {
            onOpen();
            setStatus(props.barStatus);
        }
    }, [setOpen, setStatus, props])

๋‹ค๋ฅธ ์ฝ”๋“œ์—์„œ๋„ ๋™์ผํ•œ ๋ฌธ์ œ์˜€๋‹ค. ์—ฌ๊ธฐ์—์„œ๋Š” setOpen์ด false๋ผ๋Š” ๊ฐ’์„ ๊ฐ€์ง€๊ณ  ์žˆ์œผ๋ฏ€๋กœ, ๋ฐฐ์—ด์— ๋“ฑ๋กํ•ด์ฃผ์–ด์•ผ ํ•˜๊ณ , setStatus๋„ ๋งˆ์ฐฌ๊ฐ€์ง€๋‹ค. ์—…๋ฐ์ดํŠธ๊ฐ€ ๋˜๋Š” state ๊ทธ ์ž์ฒด์ธ props๋„ ๋ฐฐ์—ด์— ๋“ฑ๋กํ•ด์ค€๋‹ค.