[React] Understand the React Hook Flow

Understanding the order in which React hooks are called can be really helpful in using React hooks effectively. This chart can be really helpful in understanding this, and in this lesson we’ll explore the lifecycle of a function component with hooks with colorful console log statements so we know when one phase starts and when it ends.

I recommend you watch this one slowly and watch it as many times as you need to. Also definitely play around with the code yourself until you feel relatively comfortable with this. Understanding all of this is not critical to your success with using React, and most of the time you won’t need to think about this at all, but understanding it can help you at times.

  1. Lazy init useState will be call only once
  2. useEffect will be called everytime when the Component get rendered
    1. If useEffect has no dep, it will be called everytime when rendering happens
    2. If useEffect has empty dep, it will NOT be called during rendering happens
    3. If useEffect has deps and that changes, it will be called during rendering happens
  3. Cleanup function for useEffect will be called for next rendering
    1. If useEffect has no dep, cleanup will be called
    2. If useEffect has empty dep, cleanup will NOT be called
    3. If useEffect has deps and that changes, cleanup will be called
  4. App render (if needed) always happen first
    1. Then follow up child component (rendering, useState, useEffect cleanup, useEffect)
    2. Then App (useState, useEffect cleanup, useEffect)

Source: https://egghead.io/lessons/react-understand-the-react-hook-flow

猜你喜欢

转载自www.cnblogs.com/Answer1215/p/12595439.html