Hooks in React

Hooks in React

21 October 2021

What is a Hook?

Hooks are the functions that let you work with the state and lifecycle components of React by using function components. Hooks is a concept which allows us to use React inside a function, we don’t need to define classes for it.

Introduction to Hooks

It’s always stressful to reuse a stateful logic between components. Can use state and other React without defining a class. Also without changing the hierarchy of the component we can reuse the stateful logic.

We often have to take care of components that begin simply but grow into an unmanageable stateful logic and side effects. Each lifecycle method may contain a mixture of unrelated logic. For instance, a component might perform API calling to fetch some data which can be done in the lifecycle method componentDidMount and componentDidUpdate.

An equivalent componentDidMount method can additionally have some unrelated logic that calls event listeners, Mutually related code that changes or works together gets split into different parts, but completely unrelated code finishes up combined during a single method. This might lead to inconsistency or even introduce bugs.

To overcome this, using Hooks we can separate one component into smaller functions supporting what pieces are related rather than forcing a split supported lifecycle method.

Rules

  • Should only call the hooks at the Top most level.
  • Should only call the hooks from the React Function not from class.

Effect

useEffect, ability to perform side effects inside a functional component. It most likely works as the lifecycle methods “componentDidMount”, “componentDidUpdate”, and “componentWillUnmount” in React classes, but unified into one API.

State

After the introduction of ES6 we have no “this” in a functional component, so we can’t use this.state. Instead, we can call the useState Hook inside our functional component for the using the state. It will only take a single argument that is the initial state.

search

Blog Categories

Request a quote