Hooks in React and their Use

Posted By : Pushkar Bisht | 25-Jul-2024

ReactJS

Loading...

Introduction

React, a popular JavaScript library for building user interfaces, it is released by Facebook in 2013. One of the most outstanding features react is react hooks, which is introduced in React 16.8.

In this article we will explore what React Hooks , their advantages, why they were needed, and what developers used before their introduction..

What Are React Hooks

React Hooks are functions for react that let developers "hook into" React state and life cycle features from function components. Hooks allow you to use state and other React features without writing a class.

There are several hooks which are used in react some them most common used hooks are as:-

a:- useState

b:- useEffect

c :-useContext

Some more react hooks are as:-

useReducer

useRef

useImperativeHandle

useLayoutEffect

useInsertionEffect

We can also make our custom react by using the existing hooks.

Before React Hooks What approach we used

Class Components: Before hooks, class components, the primary way to manage state and life cycle methods in React using this.setstate to update state and various life cycle methods.

Higher-Order Components (HOCs): HOCs were functions that took a component and returned a new component with added props or state. They were a way to reuse logic but often led to deeply nested component trees.

Render Props: Render props were a pattern where a component with a render prop would receive a function that returned a React element, allowing shared logic between components. However, this often resulted in verbose and hard-to-follow code.

Advantages of React Hooks

a:-Simplified Code and Readability

b:-Re-usability of Logic

c:- Improved Performance

d:- No More 'this' Keyword

Example of using React Hook

In this example we going to use use state hook and useEffect hook of react and making a simple stopwatch the code is given below:->

This simple example shows how hooks can be used to manage state and side effects in a function component, resulting in clean and readable code.