반응 후크 - useEffect

  • What is useEffect?
  • How Do You Use It?
  • Controlling When useEffect is Called
  • The Dependency Array
  • Cleaning Up

  • useEffect란?

    If you're familiar with the lifecycle methods of class based components (componentDidMount, componentDidUpdate, etc..), the useEffect hook is basically all of those methods rolled up into one convenient function. If you're not familiar with those lifecycle methods, you're very lucky 😂 😭.

    useEffect is a function that you can configure to run every time a component mounts.. or unmounts.. or only on the initial render.. You can reach out to a third party API, or your own backend to retrieve data. It's very powerful. It's also not as complicated as it may seem.

    어떻게 사용합니까?



    React에서 가져와 시작합니다. 명명된 가져오기이므로 중괄호 안에 있습니다.

    import { useEffect } from 'react';
    


    앞서 말했듯이 함수입니다. 그래서 당신은 그 기능을 호출합니다.

    useEffect()
    


    익명 함수를 해당 함수에 인수로 전달합니다. 이것이 바로 useEffect가 호출될 때 실행하려는 코드입니다.

    useEffect(() => {
        // executable code here.
        // grab data, update state, etc..
    })
    


    useEffect가 호출되는 시점 제어

    So we're passing a function into useEffect. As of now, that function (and useEffect itself) will be called everytime the component re-renders. If there's an input and the user is typing, that component will re-render on every keystroke.

    If you're reaching out to your backend to retrieve some data, you probably don't want to do that on every keystroke.

    That's where the dependency array comes in.

    종속성 배열

    The function we're sending into useEffect is an argument. It can also take a second argument, which is a dependency array.

    useEffect(() => {
        // this function is an argument
    }, [/* this array is, too */])
    

    If you put a property in this array, useEffect will only be called when that property changes.

    Except for the initial render.
    useEffect will always run at least
    once; on the initial render.

    So let's say you have some state. We'll use a counter example. If you want useEffect to run only when that count property changes, you'll put count in the dependency array.

    useEffect(() => {
        console.log(count)
    }, [count])
    

    Now let's say you want useEffect to run on the initial render, but not on any re-render. No matter what properties change. For that, you'd pass an empty dependency array.

    useEffect(() => {
        console.log(count)
    }, [])
    

    Here, you're essentially telling
    useEffect to run when these
    properties change. Then listing
    no properties.

    청소

    You know that function that we send into another function? Well, that function can return something...

    ...another function.



    알겠습니다.

    반환할 수 있는 함수는 정리 함수입니다. 여기에서 구독을 취소하거나 더 이상 필요하지 않은 setTimeout을 지울 수 있습니다.

    예를 들어, 9초 후에 호출되어야 하는 setTimeout이 있고 사용자가 입력하는 경우(많은 재렌더링 발생) 배경에서 9초 타이머가 진행되는 것을 원하지 않습니다. 따라서 clearTimeout인 함수를 반환합니다.

    useEffect(() => {
        const timer = setTimeout(() => {
            console.log('time!')
        }, 9000)
        return () => {
            clearTimeout(timer)
        }
    }, [])
    


    이제 해당 구성 요소가 다시 렌더링될 때마다(또는 사용자가 다른 페이지로 이동하고 타이머가 더 이상 필요하지 않은 경우) 비동기 시간 초과는 백그라운드에서 메모리를 사용하지 않습니다.

    결론

    useEffect is a very powerful part of React. It may seem like a lot at first, but once you understand it and use it a couple times, it's not so bad.

    I have a YouTube video with a few different examples. I also show exactly when useEffect is being called in different situations, and how to have more control over it.

    Hope this helped somebody and thank you for reading!

    -Andrew

    좋은 웹페이지 즐겨찾기