DEV Community

Cover image for Custom hooks in React
Shasheesh Purohit
Shasheesh Purohit

Posted on

Custom hooks in React

Custom hooks are a way to reuse stateful logic across your React components. They allow you to extract stateful logic from a component, and share that logic with other components that might need it. This can be especially useful if you find yourself repeating the same logic in multiple components, or if you want to abstract away complex logic so that your components are easier to understand and maintain.

To create a custom hook, you simply need to create a function that follows a specific naming convention: it must start with the word "use," and it must contain at least one call to the built-in hook useState or useEffect. Here's an example of a simple custom hook that keeps track of the window width and height:

import { useState, useEffect } from 'react';

function useWindowDimensions() {
  const [width, setWidth] = useState(window.innerWidth);
  const [height, setHeight] = useState(window.innerHeight);

  useEffect(() => {
    const handleResize = () => {
      setWidth(window.innerWidth);
      setHeight(window.innerHeight);
    };

    window.addEventListener('resize', handleResize);

    return () => {
      window.removeEventListener('resize', handleResize);
    };
  }, []);

  return { width, height };
}
Enter fullscreen mode Exit fullscreen mode

This custom hook uses the useState and useEffect hooks to keep track of the window width and height. It sets up an event listener to listen for window resize events, and updates the width and height state variables whenever the window is resized.

To use this custom hook in a component, you simply need to call it like a regular function. Here's an example of how you might use the useWindowDimensions hook in a component:

import React from 'react';
import { useWindowDimensions } from './useWindowDimensions';

function MyComponent() {
  const { width, height } = useWindowDimensions();

  return (
    <div>
      The window is {width}px wide and {height}px tall.
    </div>
  );
}
Enter fullscreen mode Exit fullscreen mode

This component will display the current window dimensions whenever it renders. The useWindowDimensions hook handles all of the state management and event handling, so the component can focus on rendering the UI.

Custom hooks are a powerful tool that can help you write more reusable and maintainable code in your React applications. They allow you to abstract away complex logic and share it across multiple components, making it easier to build and maintain large, interactive applications.

Top comments (1)

Collapse
 
sraman profile image
S.R. Aman

👏🏽