Hooks in React
By Komal Singh
Overview of Hooks
• React Hooks were introduced to address several limitations
and challenges associated with class components in React.
• React Hooks are functions that enable you to use state and other
React features in functional components.
• They were introduced in React version 16.8 as a way to write
reusable logic across components without the need for class
components.
• Hooks are a new feature addition in React version 16.8 which allow
you to use React features without having to write a class
• Ex: State of a Component
• Limitations of Class Components:
• Complexity: Class components often lead to complex
and verbose code, especially when dealing with stateful logic
and lifecycle methods.
• This complexity can make code harder to understand
and maintain.
• Reusability: With class components, it's challenging
to reuse stateful logic across components.
React Hooks as a Solution:
• Simplify State Management: React Hooks, such as useState,
allow functional components to hold and manage state
within themselves without the need for class components.
• This simplifies state management and reduces the
overall complexity of the code.
• Promote Reusability: Hooks enable the creation of custom
hooks, allowing developers to encapsulate and reuse stateful
logic across multiple components.
• This promotes code reuse, modularity, and maintainability.
• Eliminate this Binding: Hooks operate within the lexical scope
of functional components, eliminating the need for this binding
and reducing boilerplate code.
• This leads to cleaner and more concise code, making it easier
to read and understand.
The most commonly used built-in hooks are:
• useState: Allows functional components to hold and manage
state within themselves.
• useEffect: Enables functional components to perform side
effects such as data fetching, subscriptions, or DOM
manipulation.
• Additionally, you can create your own custom hooks to
encapsulate and reuse stateful logic across components.
• Hooks offer several benefits over class components,
including simpler and more concise code, improved
reusability, better encapsulation of logic, and enhanced
component composition.
Rules of hooks
• Hooks are normal JavaScript functions, but they impose
some additional rules :
• Hooks are called only at the top level of a component.
• Do not call Hooks inside loops, conditions, or nested
functions.
• Hooks are called only from React functional Components.
• Do not call Hooks from regular JavaScript functions.
• There is one other way to call Hooks i.e. in your own
custom Hooks
Types of hooks
• Built-In Hooks :
• useState Hooks
• useEffect Hook
• useRef Hook
• useCallback Hook
• useMemo Hook
• useContext Hook
• useReducer Hook
• Custom Hooks : You can create your own custom hooks if you have
stateful logic that is needed by multiple components in your
application.
useState Hook
• The useState hook is one of the most fundamental hooks provided by React.
• It allows functional components to hold and manage state within
themselves.
• Here's a detailed explanation of the useState hook:
• Syntax:
• const [state, setState] = useState(initialState);
• useState is a function provided by React.
• It takes one argument: the initial state value.
• It returns an array containing two elements:
• state: the current value of the state variable.
• setState: a function to update the state variable.
• Usage:
• Initialize a state variable with useState and provide an
initial value.
• Use the state variable to access the current state value.
• Use the setState function to update the state variable.
Example:
• import React, { useState } from 'react';
• function Counter() {
• // Define a state variable 'count' and its setter function 'setCount'
• const [count, setCount] = useState(0);
• return (
• <div>
• <p>Count: {count}</p>
• <button onClick={() => setCount(count + 1)}>Increment</button>
• </div>
• );
• }
• In this example, useState(0) initializes a state variable count
with an initial value of 0.
• The count variable represents the current count value.
• setCount is a function that updates the count state when
invoked. It increments count by 1 when the button is clicked.
• Benefits:
• Simplifies state management in functional components.
• Eliminates the need for class components to hold state.
• Enables better encapsulation of state within components.
• Facilitates cleaner and more concise code.
Rules:
• Rules:
• Call useState at the top level of your component.
• Do not call useState inside loops, conditions, or nested
functions.
• The order of calls to useState must be consistent
between renders.
UseEffect hook
• The useEffect hook is another fundamental hook provided
by React.
• It enables functional components to perform side effects
such as data fetching, subscriptions, or DOM
manipulation. Here's a detailed explanation of the
useEffect hook:
• Syntax:
• useEffect(() => {
• // Effect code
• }, [dependencies]);
• useEffect is a function provided by React.
• It takes two arguments:
• A function that represents the effect to be performed.
• An optional array of dependencies that determines
when the effect should re-run.
• The function passed to useEffect is known as the effect
function.
Usage:
• Use the effect function to perform tasks such as data
fetching, subscriptions, or DOM manipulation.
• Use the optional dependencies array to specify values
that the effect depends on.
• If any of the dependencies change between renders,
the effect will re-run.
Example
• import React, { useState, useEffect } from 'react';
• function Example() {
• const [count, setCount] = useState(0);
• // Effect to update document title
• useEffect(() => {
• document.title = `Count: ${count}`;
• }, [count]); // Run the effect whenever 'count' changes
• return (
• <div>
• <p>Count: {count}</p>
• <button onClick={() => setCount(count + 1)}>Increment</button>
• </div>
• );}
• In this example, useEffect updates the document title
whenever the count state changes.
• The effect function sets the document title to include
the current count value.
• The count variable is listed in the dependencies array,
so the effect will re-run whenever count changes.
Benefits:
• Enables performing side effects in functional components.
• Facilitates integrating with external APIs, libraries, and browser APIs.
• Promotes separation of concerns by keeping side effects separate
from component rendering logic.
• Provides a cleaner alternative to lifecycle methods in class
components.
• The useEffect hook is a powerful tool for managing side effects in
React functional components. It allows you to incorporate
asynchronous and imperative code in a declarative and composable
manner, enhancing the flexibility and expressiveness of your
components.