React useEffect in depth / use of useEffect?

感情迁移 提交于 2020-05-21 00:33:26

问题


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 paraments
 useEffect(()=>{})

2.useEffect with second paraments as []
  useEffect(()=>{},[])

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

回答1:


useEffect(callback)

Runs on every component render.

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

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

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 (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.



回答2:


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




回答3:


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



来源:https://stackoverflow.com/questions/59841800/react-useeffect-in-depth-use-of-useeffect

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!