Deepali's Blog

Introduction to React Hooks

J

John Smith

November 20, 2023

Introduction to React Hooks

Introduction to React Hooks

React Hooks were introduced in React 16.8 as a way to use state and other React features without writing a class. They allow you to "hook into" React state and lifecycle features from function components.

Why Hooks?

Before Hooks, you had to use class components if you needed state or lifecycle methods. This led to complex components and made it difficult to reuse stateful logic between components. Hooks solve these problems by:

- Allowing you to reuse stateful logic without changing your component hierarchy

- Organizing related code in one place instead of splitting it across lifecycle methods

- Using functions instead of classes (which can be confusing with 'this')

useState: Managing State

The useState hook lets you add state to functional components:

import React, { useState } from 'react';

function Counter() {

const [count, setCount] = useState(0);

return (

<div>

<p>You clicked {count} times</p>

<button onClick={() => setCount(count + 1)}>

Click me

</button>

</div>

);

}

useEffect: Handling Side Effects

The useEffect hook lets you perform side effects in function components:

import React, { useState, useEffect } from 'react';

function Example() {

const [count, setCount] = useState(0);

useEffect(() => {

document.title = `You clicked ${count} times`;

});

return (

<div>

<p>You clicked {count} times</p>

<button onClick={() => setCount(count + 1)}>

Click me

</button>

</div>

);

}

Other Common Hooks

- useContext: Access React context

- useReducer: Manage complex state logic

- useRef: Access DOM elements directly

- useMemo and useCallback: Optimize performance

Custom Hooks

You can create your own hooks to extract and reuse stateful logic:

function useWindowWidth() {

const [width, setWidth] = useState(window.innerWidth);

useEffect(() => {

const handleResize = () => setWidth(window.innerWidth);

window.addEventListener('resize', handleResize);

return () => {

window.removeEventListener('resize', handleResize);

};

}, []);

return width;

}

Hooks have transformed how React applications are built, making code more readable, maintainable, and reusable.