简体   繁体   中英

Function prop useEffect best practices

I'm getting a load function prop from a connected container and I'm considering two options to use with useEffect but I don't know which one might be considered best practice, here the first one:

function MyComponent({ load }) {
  useEffect(() => {
    load();
  }, [load]);
}

Here's the second one I've read about using useRef :

function MyComponent({ load }) {
  const loadRef = useRef({ loadData: load});

  useEffect(() => {
    const { loadData } = loadRef.current;

    loadData(); 
  }, []);
}

Which one should I use and why?

Using hooks, what you probably want is to use useDispatch()

and call useDispatch(actionCreator) inside the useEffect.

You need to call a Redux function once?

just use

useEffect(() => {
  load();
}, []);

You might not even need to add load to the brackets, if the loading doesn't stop that means your component isn't re-rendering after it stops and you need to put the object that tells the life cycle method to re-render because the loading is done, in most cases its an isLoading boolean in local state.

To call something once, when the component just mounted, you can use hook useEffect with empty dependencies:

  useEffect(() => {
    load()
  }, [])

More info https://reactjs.org/docs/hooks-effect.html

The load function can be taken from props, if you will map it from redux via connect function. More info https://react-redux.js.org/api/connect

Just use:

  useEffect(() => {
      load();
    }
  []);

It is only a callback. You should not pass the load if you would like to call it once. From the react docs https://reactjs.org/docs/hooks-effect.html :

In the example above, we pass [count] as the second argument. What does this mean? If the count is 5, and then our component re-renders with count still equal to 5, React will compare [5] from the previous render and [5] from the next render. Because all items in the array are the same (5 === 5), React would skip the effect. That's our optimization.

Of course you can use the dispatching through the redux, however i guess in this easy situation dispatching event is a little bit dirty. So in my opinion use of useEffect hook is cleaner.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM