React useEffect in depth / use of useEffect?

后端 未结 3 1579
佛祖请我去吃肉
佛祖请我去吃肉 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:27

    3.useEffect with some arguments passed in the second parameter useEffect(()=>{},[arg])

    it will run first then it will run again if arg change

    Your forget also to ask what about the return inside the useEffect... Its uses for cleanup it will run when component dismount

    0 讨论(0)
  • 2020-11-28 16:28

    If you’re familiar with React class lifecycle methods, you can think of useEffect Hook as componentDidMount, componentDidUpdate, and componentWillUnmount combined.

    1.useEffect with no second paraments : This is used when we want something to happen either when the component just mounted, or if it has been updated. Conceptually, we want it to happen after every render.

    2.useEffect with second paraments as [] : This is used when we want something to happen at the time of mounting of the component, if only executes once at the time of mounting.It is closer to the familiar componentDidMount and componentWillUnmount.

    3.useEffect with some arguments passed in the second parameter:This is used when we want something to happen at the time when the pramter passed eg. args have changed in your case.

    For more info. check here: https://reactjs.org/docs/hooks-effect.html

    0 讨论(0)
  • 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.
    0 讨论(0)
提交回复
热议问题