Home:ALL Converter>React Hooks Component vs Class Component

React Hooks Component vs Class Component

Ask Time:2019-12-02T10:43:20         Author:Richard

Json Formatter

I've been reading about hooks and some of their benefits, but it seems like there's some comparisons between apples and oranges, and at high level, hook components are just faux-classes with dependency injection. For example, classes setState vs hooks setState. You cant really compare the two because they behave differently. The difference in behavior is not due to functions or classes, but because of react implemented the two functions. The values from useState and other hooks are just faux class properties that get resolved by a dependency container, and are created and destroyed after every render. It seems like react is saying to use hook components over classes because classes confuse people and machines, but are essentially using class concepts, but calling them something else. Good and bad code is independent of classes and functions, and depends on how much you break down the problem into small pieces, so moving to functional components with hooks seems like a lateral movement. I really like the concept of useEffect, but am missing why it's behavior couldn't be ported to classes. I'm not seeing how nested functions are cleaner than class functions.

Author:Richard,eproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/59132002/react-hooks-component-vs-class-component
oemera :

Hooks are revoulutionary imo. I worked with classes for a very small time and was happy to discover hooks.\n\nHere is a small list of obvious improvements:\n\nHooks will save you a lot of boilerplate. You don't have constructors with super(props) anymore. Also you get rid of this and especially the cumbersome .bind(this) calls.\n\nYou can seperate your state with multiple useState hooks instead of having a very big state object. Also you can easily reuse similar state logic or logic in general with your own custom hooks. This actually is one of the biggest benefits since you get rid of renderProps and mostly HOCs too. You have just one simple and intuitive way to share logic across components.\n\nThe other thing is that you get rid of the Consumer part when using context and simply use useContext. \n\nuseEffect completely replaces all life cycle hooks and eliminates the awkard use of ComponentWillReceiveProps with the dependencies array.\n\nIn general I think it's way more intuitive to work with functions and hooks instead of classes. In fact you only need functions now whereas before you had to use class components for stateful components and should use functions for stateless components. This alone shows how using functions over classes was desired all the time but it was just not possible back then.",
2019-12-02T04:17:35
yy