Pato Loco
Pato Loco

Reputation: 1244

Does hooks simplify your code or is just a matter of taste?

Particularly speaking about state I've been playing around with hooks and honestly I don't see many benefits comparing to class components. It is said that a benefit is that you can add state to a function component when required in the future but to me transforming into a class is not a big deal.

Upvotes: 4

Views: 114

Answers (2)

Hbarna
Hbarna

Reputation: 435

Here are some of the benefits using hooks, taken from the React's documentation.

  1. Hooks allow you to reuse stateful logic without changing your component hierarchy. This makes it easy to share Hooks among many components or with the community.

With Hooks you can reuse your API calls and make your code more usable, which leads to less time spent on rewriting your expected behaviour.

  1. 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. You may also opt into managing the component’s local state with a reducer to make it more predictable.

This makes your components more compact, which in turn makes your code more readable, which is what you would want to see in your everyday code.

  1. Classes confuse both people and machines

In javascript this is not interpreted as the same as other languages and also whether to use classes or functional components confuse developers, why would you need to choose one if you can do everything functionally? Also for performance issues when folding the components classes are not minimized as well as functions and for React to stay relevant it should be optimized.

Upvotes: 1

MNN TNK
MNN TNK

Reputation: 372

Why Hooks ?

Without hooks you can’t reuse stateful logic between components

  • you may be familiar with patterns like render-props and HOCs that try to solve this.
  • But these patterns require you to restructure your components
  • Hooks allow you to reuse stateful logic without changing your component hierarchy.

Life cycles are weird

  • Related code gets split apart, but completely unrelated code ends up combined in a single lifecycle method
  • Hooks let you split unrelated pieces apart and group related pieces together in one function

Classes are not cool

  • Too much code, yuck!
  • Have to bind event handlers
  • Have to understand how ‘this’ works

Upvotes: 4

Related Questions