Introducing React Hooks
In 2018, at the React Conference “Hooks” was officially Introduced to React.
Hooks arrived as a saviour for developers who were struggling in maintaining hundreds of states for hundreds of components.
They let you use state and other React features without writing a class. Now, you can kick out classes from your components.
No need to worry, There are no plans to remove classes from React permanently, yet
You can adopt Hooks gradually,
Hooks work side-by-side with existing code so there is no rush to migrate to Hooks.
You don’t have to learn or use Hooks right now if you don’t want to.
WHY GO FOR HOOKS?
You might be thinking why you need to learn one more feature? The answer is here:
It helps when you need to maintain too many components and states.
Completely opt-in.
You can try Hooks in a few components without rewriting any existing code.
A “wrapper hell” of components surrounded by layers of providers, consumers, higher-order components, render props, and other abstractions. While we could filter them out in DevTools, this points to a deeper underlying problem: React needs a better primitive for sharing stateful logic, here Hooks made an appearance.
With Hooks code Reusability is improved, you can extract stateful logic from a component so it can be tested independently and reused. 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.
render props and higher-order components try to solve some problems but make code harder to follow, because it requires to restructure your components.
components might perform some data fetching in componentDidMount and componentDidUpdate. However, the same componentDidMount method might also contain some unrelated logic that sets up event listeners, with cleanup performed in componentWillUnmount. Mutually related code that changes together gets split apart, but completely unrelated code ends up combined in a single method. This makes it too easy to introduce bugs and inconsistencies.
It’s not always possible to break these components into smaller ones because the stateful logic is all over the place. It’s also difficult to test them. This is one of the reasons many people prefer to combine React with a separate state management library.
class components can encourage unintentional patterns that make these optimizations fall back to a slower path.
How Hooks Affect the Coding Style
Say bye! to class
Without Hooks:
Class Components
See the complete code
Top comments (1)
try setup in react:
codesandbox.io/s/concent-guide-xvcej
function component and class component share business logic code easily.