How combine 3 lifecycles in one in useEffect in the following case?

Viewed 25

I have a useEffect where currently get from the redux the data and also clean up it during the unmounting:

  useEffect(
     dispatch(getData...)
    () => {
      dispatch(cleanData...)
    },
    [url]
  );

When I set the url as dependency for using as componentDidupdate and updating the component if url is changed it throws some warnings in the console about not being able to work with unmounted component while functionality seems to work. What is the ideal way to have these 3 lifecycle methods in the same place for the useEffect?

1 Answers

useEffect expects two arguments. Callback Function that will get called at the initial render and when the dependencies gets changed. Second argument is dependency array.

So you can call dispatch function on initial render and on change of url . You have to return a function that is a cleanup function.

useEffect(() => {
     dispatch(getData)
    return () => {
      dispatch(cleanData)
    }
},[url]);
Related