09. Hook Flow

Hook이 동작하는 순서에 대해서 설명한다.

현재까지 배운 useEffect와 useState의 동작하는 순서에 대해서 말하겠다.

App render -> useState : initial -> rendering End -> useEffect : 등록한 순서대로

작동을 한다. 여기서 상기해야할 점은 useEffect는 사이드 이펙트를 관리하는 Hook이기 때문에 전부 그려지고 난뒤에, 작동을 하는 것을 알 수 있다.

flow chart

<body>
  <div id="root"></div>
  <script src="https://unpkg.com/react@16.12.0/umd/react.development.js"></script>
  <script src="https://unpkg.com/react-dom@16.12.0/umd/react-dom.development.js"></script>
  <script src="https://unpkg.com/@babel/standalone@7.8.3/babel.js"></script>
  <script type="text/babel">
    // https://github.com/donavon/hook-flow

    function Child() {
      console.log('%c    Child: render start', 'color: MediumSpringGreen')

      const [count, setCount] = React.useState(() => {
        console.log('%c    Child: useState callback', 'color: tomato')
        return 0
      })

      React.useEffect(() => {
        console.log('%c    Child: useEffect no deps', 'color: LightCoral')
        return () => {
          console.log(
            '%c    Child: useEffect no deps cleanup',
            'color: LightCoral',
          )
        }
      })

      React.useEffect(() => {
        console.log(
          '%c    Child: useEffect empty deps',
          'color: MediumTurquoise',
        )
        return () => {
          console.log(
            '%c    Child: useEffect empty deps cleanup',
            'color: MediumTurquoise',
          )
        }
      }, [])

      React.useEffect(() => {
        console.log('%c    Child: useEffect with dep', 'color: HotPink')
        return () => {
          console.log(
            '%c    Child: useEffect with dep cleanup',
            'color: HotPink',
          )
        }
      }, [count])

      const element = (
        <button onClick={() => setCount(previousCount => previousCount + 1)}>
          {count}
        </button>
      )

      console.log('%c    Child: render end', 'color: MediumSpringGreen')

      return element
    }

    function App() {
      console.log('%cApp: render start', 'color: MediumSpringGreen')

      const [showChild, setShowChild] = React.useState(() => {
        console.log('%cApp: useState callback', 'color: tomato')
        return false
      })

      React.useEffect(() => {
        console.log('%cApp: useEffect no deps', 'color: LightCoral')
        return () => {
          console.log('%cApp: useEffect no deps cleanup', 'color: LightCoral')
        }
      })

      React.useEffect(() => {
        console.log('%cApp: useEffect empty deps', 'color: MediumTurquoise')
        return () => {
          console.log(
            '%cApp: useEffect empty deps cleanup',
            'color: MediumTurquoise',
          )
        }
      }, [])

      React.useEffect(() => {
        console.log('%cApp: useEffect with dep', 'color: HotPink')
        return () => {
          console.log('%cApp: useEffect with dep cleanup', 'color: HotPink')
        }
      }, [showChild])

      const element = (
        <>
          <label>
            <input
              type="checkbox"
              checked={showChild}
              onChange={e => setShowChild(e.target.checked)}
            />{' '}
            show child
          </label>
          <div
            style={{
              padding: 10,
              margin: 10,
              height: 30,
              width: 30,
              border: 'solid',
            }}
          >
            {showChild ? <Child /> : null}
          </div>
        </>
      )

      console.log('%cApp: render end', 'color: MediumSpringGreen')

      return element
    }

    ReactDOM.render(<App />, document.getElementById('root'))
  </script>
</body>
  • 위의 코드를 실행해보면 Hook Flow에 대해서 알 수 있는데, 렌더링시

    Parents render -> Parents useState Call -> Parents render end -> Child render -> child useState Call -> Child render end -> (Child useEffect clean up) -> Child useEffect -> (Parents useEffect clean up) -> Parents useEffect

    cleanup은 최초 렌더시 되지 않지만, 만약 변경사항이 존재할때에는 cleanup들이 먼저 발생을 하고 useEffect가 작동한다.

  • 또한, vue와 비슷하게 moutend 까지는 Parents Component가 먼저하지만, 그 이후로는 Child Component가 모든 과정이 끝나야 Parents의 UseEffect를 하는 것을 알 수 있다.

  • 이 부분에 대해서 다른 Hook을 공부하고 더 업데이트를 해야겠다.

+ Recent posts