react-use icon indicating copy to clipboard operation
react-use copied to clipboard

[Discussion] Remove lifecycle hooks cause they violates the motivation of why React team create hooks.

Open tianzhich opened this issue 4 years ago • 3 comments

Hi, the react-use team, thank you for creating this useful library.

There is one question that confuse me for a long time. Do we really need lifecycle hooks? Recently I read the motivation of why React team create hooks. In which they said:

... components might perform some data fetching in componentDidMount and componentDidUpdate... To solve this, Hooks let you split one component into smaller functions based on what pieces are related (such as setting up a subscription or fetching data), rather than forcing a split based on lifecycle methods.

IMO the react team introduces hooks to avoid the code splitting based on lifecycle methods and make developers focused more on business logic. So the lifecycle method is unnecessary.

There is another bad case when I refactor the codebase written by my colleague. She used useMount like what she did with class components. The data fetching logic repeats in useMount and useEffect which makes code hard to understand and maintain.

And also, the useMount hook hides the fact that the effect should be rerun if its dependencies change, by forcing leave its dependencies empty:

useMount(fn) = useEffect(()=> {
   fn();
}, []);

This fact is how the react hooks, especially the useEffect hook works. There is no need to use useMount if you use useEffect correctly(for example, use a constant value instead of a variable to empty the dependency array).

So why do we need to use these lifecycle hooks if they violate(maybe) the motivation of why React team created hooks? Or more accurately, hide the fact of how hooks run.

tianzhich avatar Jan 13 '22 04:01 tianzhich

I also found a note in this section:

If you pass an empty array ([]), the props and state inside the effect will always have their initial values. While passing [] as the second argument is closer to the familiar componentDidMount and componentWillUnmount mental model, there are usually better solutions to avoid re-running effects too often.

So, there are better solutions to avoid re-running effects too often(or just want to run on componentDidMount). But some developers may use useMount directly and give up trying to find better solutions. This also hides the fact of how the effect hook works. Even the lifecycle mental model had a great impact. But we can guide developers to learn hooks instead of hiding the fact. What do you think?

tianzhich avatar Jan 13 '22 09:01 tianzhich

useMount could actually fix the double calling of side-effects introduced with react 18's strict mode. Also useEffectOnce is called twice within <React.StrictMode>

igl avatar Jun 14 '23 09:06 igl

Also need to remove useUnmount

ByteWither avatar Sep 06 '23 20:09 ByteWither