REACT Tutorial



CUSTOM HOOKS IN REACT


Custom Hooks in React

Custom Hooks allow you to extract and reuse stateful logic across multiple components. They are JavaScript functions whose names start with use and can call other hooks internally.

Why create Custom Hooks?
To share reusable logic like fetching data, form validation, or animation between components without duplicating code.

Creating a Simple Custom Hook

import { useState, useEffect } from 'react';

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

  useEffect(() => {
    function handleResize() {
      setWidth(window.innerWidth);
    }

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

  return width;
}

export default useWindowWidth;
  

Using the Custom Hook in a Component

import React from 'react';
import useWindowWidth from './useWindowWidth';

function ShowWidth() {
  const width = useWindowWidth();

  return (
    <div style={{ textAlign: 'center', marginTop: '30px', fontSize: '18px' }}>
      <p>Current window width: <strong>{width}px</strong></p>
    </div>
  );
}
  

Here, useWindowWidth listens to window resize events and provides the current window width. This logic is cleanly separated and can be reused anywhere by just calling the hook.

Custom Hooks are a powerful way to keep your React code DRY (Don't Repeat Yourself) and maintainable.

🌟 Enjoyed Learning with Us?

Help others discover Technorank Learning by sharing your honest experience.
Your support inspires us to keep building!

Leave a Google Review