Open In App

React Hooks

In React, Hooks are reusable functions that provide access to state in React Applications. Hooks were introduced in the 16.8 version of React. Hooks give access to states for functional components while creating a React application. It allows you to use state and other React features without writing a class.

What are React Hooks?

React Hooks provide functional components with the ability to use states and manage side effects. They were first introduced in React 16.8, and allow developers to hook into the state and other React features without having to write a class. They provide a cleaner and more concise way to handle state and side effects in React applications.

Although Hooks generally replace class components, no plans exist to remove classes from React.

Note: Hooks cannot be used with class components

When to use React Hooks

If you have created a function component in React and later need to add state to it, you used to have to convert it to a class component. However, you can now use a Hook within the existing function component to add a state. This way, you can avoid having to rewrite your code as a class component.

Types of React Hooks

The Built-in React Hooks are:

1. React State Hooks

State Hooks stores and provide access to the information. To add state in Components we use:

const [count, setCount] = useState(0)

2. React Context Hooks

Context hooks make it possible to access the information without being passed as a prop.

const context = useContext(myContext);

3. React Ref Hooks

Refs creates the variable containing the information not used for rendering e.g. DOM nodes.

const textRef = useRef(null);

4. Effect Hooks:

Effects connect the components and make it sync with the system. It includes changes in browser DOM, networks and other libraries.

useEffect(()->{
// Code to be executed
}, [dependencies] )

5. React Performance Hooks:

Performace hooks are a way to skip the unnecessary work and optimise the rendering preformance.

const memoizedValue = useMemo(functionThatReturnsValue, arrayDependencies)

To prioritize rendering we can use these:

6. React Resource Hooks:

It allows component to access the resource without being a part of their state e.g., accessing a styling or reading a promise.

const data = use(dataPromise);

7. Additional React Hooks:

These are rarely used hooks mostly used in libraries.

Apart from these Built-in React hooks we can also create Custom Hooks in React.

You can see a Complete list of React Hooks in ReactJS Hooks Complete Reference.

Benefits of using Hooks

Hooks can improve code reusability and make it easier to split complex components into smaller functions.

Why the need for ReactJs Hooks?

There are multiple reasons responsible for the introduction of the Hooks which may vary depending upon the experience of developers in developing React application. Needs for react hooks are:

1. Use of 'this' keyword

2. Reusable stateful logics:

3. Simplifying complex scenarios:

Rules for using Hooks

Using Hooks in React

This example demonstrate the use of react useState hook in the application.

// Filename - index.js

import React, { useState } from "react";
import ReactDOM from "react-dom/client";
function App() {
    const [click, setClick] = useState(0);
    
    // Using array destructuring here
    // to assign initial value 0
    // to click and a reference to the function
    // that updates click to setClick
    return (
        <div>
            <p>You clicked {click} times</p>
            <button onClick={() => setClick(click + 1)}>
                Click me
            </button>
        </div>
    );
}

const root = ReactDOM.createRoot(
    document.getElementById("root")
);
root.render(
    <React.StrictMode>
        <App />
    </React.StrictMode>
);

Output:

We have used useState hook which lets functional components have access to states with the help of which we are able to manipulate states

gfg

Difference Between Hooks and Class Components

FeatureClass ComponentsReact Hooks
State Managementthis.state and lifecycle methodsuseState and useEffect
Code StructureSpread across methods, can be complexSmaller, focused functions
ReusabilityDifficult to reuse logicEasy to create and reuse custom hooks
Learning CurveFamiliar to OOP developersRequires different mindset than classes
Error BoundariesSupportedNot currently supported
Third-party LibrariesSome libraries rely on themMay not all be compatible yet

Important things to remember while using hooks

Article Tags :