Browse Courses

Custom Hooks

This document explains the use of useEffect and custom hooks in React including how to manage side effects, dependency arrays, and create reusable logic for function components.

This document covers the use of useEffect and custom hooks in React. It explains how to manage side effects, use dependency arrays, and create reusable logic for function components using custom hooks.


Introduction to Side Effects and useEffect

In React, a side effect is any operation that affects the application outside the component’s render process, such as data fetching, event subscriptions, DOM manipulation, or timers. The useEffect hook allows function components to perform side effects efficiently.


How useEffect Works

  • useEffect runs after the component renders.
  • It can be used to fetch data, subscribe to events, or update the DOM.
  • Side effects are asynchronous and can impact application state or UI.

Example: Fetching Data with useEffect

 1import React, { useState, useEffect } from 'react'
 2
 3function FoodList() {
 4  const [foods, setFoods] = useState([])
 5
 6  useEffect(() => {
 7    fetch('https://api.example.com/foods')
 8      .then(response => response.json())
 9      .then(data => setFoods(data))
10      .catch(error => console.error('Error:', error))
11  }, [])
12
13  return (
14    <ul>
15      {foods.map(food => (
16        <li key={food.id}>{food.name}</li>
17      ))}
18    </ul>
19  )
20}

Dependency Arrays in useEffect

The dependency array determines when the effect runs:

  • Empty array ([]): Effect runs only once on mount.
  • Specific values: Effect runs when any listed value changes.
  • No array: Effect runs after every render.

Custom Hooks in React

Custom hooks allow you to extract and reuse logic across multiple components. They are named with the use prefix and can combine standard hooks like useState and useEffect.

Example: Creating a Custom useToggle Hook

1import { useState } from 'react'
2
3function useToggle(initialValue = false) {
4  const [isToggled, setIsToggled] = useState(initialValue)
5  const toggle = () => setIsToggled(prev => !prev)
6  return [isToggled, toggle]
7}
8
9export default useToggle

Example: Using the useToggle Hook

1import React from 'react'
2import useToggle from './useToggle'
3
4function ToggleButton() {
5  const [isToggled, toggle] = useToggle()
6  return <button onClick={toggle}>{isToggled ? 'On' : 'Off'}</button>
7}

Conclusion

The useEffect hook enables function components to manage side effects, while custom hooks allow for reusable, modular logic. By understanding dependency arrays and custom hook patterns, developers can write cleaner and more maintainable React code.


FAQ

  1. To perform side effects in function components
  2. To style components
  3. To manage routing
  4. To create class components
(1) useEffect is used to perform side effects such as data fetching, subscriptions, or DOM updates in function components.

  1. The effect runs only once
  2. The effect runs after every render
  3. The effect never runs
  4. The effect only runs on unmount
(2) Omitting the dependency array causes the effect to run after every render.

  1. Custom hooks must start with the word “use”
  2. Custom hooks can use other hooks inside them
  3. Custom hooks can only be used in function components
  4. Custom hooks can be used in class components
(4) Custom hooks cannot be used in class components; they are for function components only.

  1. They control when the effect runs based on listed values
  2. They are required for all hooks
  3. They are only used for styling
  4. They are ignored by React
(1) Dependency arrays determine when the effect should re-run based on changes to listed values.

  1. Whether the hook is using the correct state and effect hooks
  2. If the hook is named with the use prefix
  3. If the hook is imported from React
  4. If the hook is used in a class component
(1) Ensure the custom hook is using the correct state and effect hooks and is implemented properly.

ScenarioBehavior
A. []1. Runs after every render
B. [count]2. Runs only once on mount
C. (no array)3. Runs when count changes
A-2, B-3, C-1.

Custom hooks allow you to extract and reuse logic across multiple React components.

True. Custom hooks enable logic reuse and cleaner code across components.

  1. It can be used to fetch data from an API
  2. It can be used to subscribe to events
  3. It can only be used in class components
  4. It can be used to set timers
(3) useEffect is only used in function components, not class components.

  1. They allow logic to be reused across multiple components
  2. They replace the need for useEffect
  3. They are only used for styling
  4. They are required for all side effects
(1) Custom hooks enable logic reuse and cleaner code across components.

  1. It manages a boolean state and provides a toggle function
  2. It fetches data from an API
  3. It handles form submissions
  4. It manages routing
(1) useToggle manages a boolean state and provides a function to toggle its value.