React Hooks

Introduction to React Hooks

Devin Munasinghe
6 min readMar 17, 2022

--

Hooks allow functional components to access state and other react life cycle features. Hooks was firstly introduced in React 16.8 version. Since then it has played a major role in react application development. Hooks are known as backward-compatible, which means it does not include any breaking changes. Also, it does not replace your knowledge and ideas about React concepts.

Reuse stateful logic

React doesn’t offer a way to attach reusable behavior to components. Hooks allows developers to extract stateful logic from a component. This logic can then be tested independently and reused. You can reuse stateful logic with React hooks without modifying your component hierarchy. Sharing hooks among many components or with the community then becomes much easier.

Problems happen before using react hooks

Over the course of five years of writing and maintaining tens of thousands of components, hooks have solved a wide range of seemingly unrelated problems in React. These are some problems:

  1. Stateful logic is difficult to reuse between components.

As mentioned above, there is no way to bind reusable functionality to components in React. In react you can use patterns such as render props and higher-order components to solve this. However, using these patterns necessitates reorganizing your components, which may be inconvenient and make code more difficult to follow.

Hooks allow you to reuse stateful logic without having to change the hierarchy of your components.

2. Components that are complex become difficult to understand.

We’ve had to maintain components that began off small but quickly evolved into a jumble of stateful logic and side effects. Each lifecycle method frequently involves a combination of logic that is unconnected to one another. In componentDidMount and componentDidUpdate, components may handle some data fetching. However, the same componentDidMount function may also include unrelated code that sets up event listeners, which would be cleaned up in componentWillUnmount. Code that is mutually connected and changes together is separated, whereas code that is wholly unrelated is grouped together in a single method. This makes it far too simple for bugs and inconsistencies to creep in.

Because the stateful logic is all over the place, it’s sometimes impossible to divide these components down into smaller pieces. It’s also tough to test them. One of the reasons why many people choose to use React in combination with a different state management library is because of this. However, this frequently creates too much abstraction, necessitating file switching and making reusing components more difficult.

However, Hooks let you split one component into smaller functions based on what pieces are related, rather than forcing a split based on lifecycle methods.

3. Both people and machines confuse by classes

A React class component is a native java script classes, so it inherited the issues of JavaScript classes, including working with this, explicitly binding methods, verbose syntax, and more.

To solve these problems, Hooks let us use more of React’s features without classes.

When to use a hook?

If you want to code a functional component, then you want to add some statea or side effects to it, previously we can do this by converting it into class. But now you can do this by using using a Hook inside the existing function component.

Rules of Hooks

  • Hooks can be called inside react functional components
  • Hooks can only be called at the top level of a component.
  • Hooks cannot be conditional, and they will not work with the class component

React Hook Types

Basic Hooks,

  • useState()
  • useEffect()
  • useContext()

Additional Hooks,

  • useReducer()
  • useMemo()
  • useCallback()
  • useImperativeHandle()
  • useDebugValue()
  • useRef()

In here, we will only consider basic react hooks,

  1. UseState()

At some point, the state of your application will change. This might be a variable’s value, an object’s value, or any other type of data in your component. We must apply a React hook called useState()in order for the changes to be reflected in the DOM.

example :

import {useState} from 'react';function App() {
const [userName, setUserName] = useState("John112");
const changeUserName = () => {
setUserName("Peter224");
};

return (
<div>
<p>My user name is {userName}</p>
<button onClick={changeName}> Click me change name </button>
</div>
);
}

export default App;

when we refer more deeply above example, you must import the useState() hook from React in order to use this hook. App is a functional component that we use.

const [userName, setUserName] = useState("John112");

Then we have created the state while giving the initial state which is “John112”. In there the state variable is userName while setUserName is the function that updates the value.

After we created a function called changeUserName to change the user name from initial value to updated value using setUserName .

const changeUserName = () => {
setUserName("Peter224");
};

When the program is executed firstly it displays the initial user name. After clicking the button it calls the changeUserName function and updates the initial user name to an updated one and assigns it to the userName variable. Then it displays the updated value.

2. UseEffect()

UserEffect is a function that gets called every time the component gets rendered. This function allows performing side effects hen data or state changes in the component. useEffect() solve problems such as how to run code when the state changes or when a props changes.

Side effects have common features which most web applications need to perform, such as:

  • Updating the DOM,
  • Fetching and consuming data from a server API,
  • Setting up a subscription, etc.

Moreover, Effects Hooks are equivalent to componentDidMount(), componentDidUpdate(), and componentWillUnmount() lifecycle methods.

In general, the React component contains two types of side effects:

  1. Effect without cleanup
  2. Effect with Cleanup

Effect without Cleanup

It’s used in useEffect, which allows the browser to update the screen without blocking it. It improves the app’s responsiveness. The following are a few instances that do not require clean-up,

  • Manual DOM mutations
  • network requests
  • logging

Example:

import React, { useState, useEffect } from 'react';function App() {
const [count, setCount] = useState(0);
useEffect(() => {
document.title = `You clicked ${count} times`;
});
return (
<div>
<p>Hey!! you have clicked {count} times</p>
<button onClick={() => setCount(count + 1)}>
Click
</button>
</div>
);
}

In this scenario, Keeping useEffect within the component allows us to access the count state variable right from the effect. As a result, no specific API is required to read it.

Effect with Cleanup

Following DOM updates, certain effects require cleanup. If we wish to set up a subscription to an external data source, for example, we must clear up memory to avoid introducing a memory leak. When the component is unmounted, React cleans away the memory. However, as we all know, effects are applied to each and every render method, not just once. As a result, before performing the effects again, React cleans away the effects from the previous render.

useEffect(() => {
const subscription = props.source.subscribe();
return () => {
// Cleaning up the subscription
subscription.unsubscribe();
};
});

3. useContext()

Even if it isn’t essential, UseContext is a fantastic technique to reduce the complexity of data transmission to various levels in the hierarchy via props.

Context APIs enable us to define an object context that stores data and makes it accessible in the hierarchy without the need to give the data as props.

First, we create a new context, which we store inNumberContexta 2-property object with two properties which are Provider and User.

const { Provider, Consumer } = React.createContext();

TheNumberContext.Provider is then rendered and a value prop is attached to it. This significance would be made available to all of the parents and their children.

The consumer will be able to read out the value for the whole subtree. Finally, we read the value using the Consumer within the Display variable.

// import useContext
import React, { useContext } from 'react';
function Display() {
const value= useContext(ValueContext);
return <div>The answer is {value}.</div>;
}

This is all about basic react hooks. hope you enjoy it. 👍

--

--