Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

reactjs
communitycreator

How to create a custom hook in React.js

Osinachi Chukwujama

What is a React hook?

A React hook is a function that lets you listen to the state and lifecycle events of a React component. Hooks are restricted to functional components.

React ships with a number of hooks that have different functions, such as:

  1. useState: represents and uses the state of a component.
  2. useEffect: handles side effects such as network calls and manual DOM updates.
  3. useRef: gets the DOMDocument Object Model representation of a React component.

What is a custom hook?

A custom hook in React.js is a user-defined hook that builds on one or more default hooks. A custom hook enables you to encapsulate functionality into a reusable hook.

For example, say you want to conditionally render a component based on the window’s screen size. JavaScript lets you add a resize event listener to the window object so you can run some logic whenever a window is resized. You can create a custom hook called useScreenSize that will detect changes in screen size and return the updated screen size.

You can structure your custom hook with the following pseudocode:

function useScreenSize() {
  /**
   * Represent screen size by an internal state using useState
   * Update the internal state in a useEffect hook whenever the screen is resized
   * Return the new screen size
   */
}

Here’s the JavaScript implementation of the pseudocode:

import { useState, useEffect } from 'react';

export function useScreenSize() {
  // Represent screen size by an internal state using useState
  const [size, setSize] = useState({
    width: window.innerWidth,
    height: window.innerHeight,
  });

  // Update the internal state in a useEffect hook whenever the screen is resized
  const handleResize = () => {
    setSize({ width: window.innerWidth, height: window.innerHeight });
  };
  useEffect(() => {
    window.addEventListener('resize', handleResize);
    return () => window.removeEventListener('resize', handleResize);
  }, []);

  // Return the screen size
  return { width: size.width, height: size.height };
}

You have to note that an event listener needs to be removed when the component that it was created in unmounts. If it isn’t removed, it may cause a memory leak, especially in an older browser like IE11. The resize event listener is removed in the return function of the useEffect hook above.

Steps to create a custom hook

  1. Analyze the scope of your hook and represent the necessary state logic with useState.
  2. Check if any side effects will be involved. Examples of side effects are API calls and event listeners.
  3. Return the desired output.

Code

The code below shows how the useScreenSize hook works. The page gets updated with the current screen size whenever the window screen is resized.

function useScreenSize() {
  const { width, height } = window.screen;

  // Represent screen size by an internal state using useState
  const [size, setSize] = useState({ width, height });

  // Update the internal state in a useEffect hook whenever the screen is resized
  useEffect(() => {
    const { width, height } = window.screen;
    setSize({ width, height });
  }, [window.screen]);

  // Return the screen size
  return { width: size.width, height: size.height };
}

export default useScreenSize

RELATED TAGS

reactjs
communitycreator
RELATED COURSES

View all Courses

Keep Exploring