React useEffect in depth / use of useEffect?

后端 未结 3 1585
佛祖请我去吃肉
佛祖请我去吃肉 2020-11-28 16:05

I am trying to understand the useEffect hook in-depth.

I would like to know when to use which method and why?

1.useEffect with no second         


        
3条回答
  •  清歌不尽
    2020-11-28 16:40

    useEffect(callback)
    

    Runs on every component render.

    Typically used for debugging, analogous to function's body execution on every render:

    const Component = () => {
      callback()
      return <>;
    };
    

    Note: There is still a difference, in execution time (see the next note). Check this sandbox logs.


    useEffect(callback,[])
    

    Runs once on a component mount.

    Usually used for initializing components state by data fetching etc.

    Note: The callback executed after the render phase (Known "Gotcha").


    useEffect(callback,[arg])
    

    Runs on change of arg value.

    "On Change" refers to shallow comparison with the previous value of arg.

    I.e compares the value of arg from the previous render and the current one, prevArg === arg ? ~Do nothing~ : callback().

    Usually used to run events on props/state change.

    Note: Multiple dependecies can be provided: [arg1,arg2,arg3...]


    • A Complete Guide to useEffect by Dan Abramov
    • useEffect API.
    • Using the effect hook - React docs.

提交回复
热议问题