Skip to content

Custom Hooks

vinibiavatti1 edited this page Sep 28, 2026 · 2 revisions

JavaScript functions starting with use that encapsulate and share reusable stateful logic between components. Whenever you need to reuse logic that depends on React Hooks, you must create a custom Hook. Every call creates a completely isolated state instance for that component.

Note: Must follow the use prefix naming rule so React's linter can enforce the Rules of Hooks inside the function.

import { useState, useEffect } from 'react';

// Custom hook
export const useDocumentTitle = (initialValue) => {
    const [title, setTitle] = useState(initialValue);

    useEffect(() => {
        document.title = title;
    }, [title]);

    return [title, setTitle];
};

// Consumer
export const Component = () => {
    const [title, setTitle] = useDocumentTitle('Home');

    return (
        <button onClick={() => setTitle('Contact')}>Contact Page</button>
    );
};

Clone this wiki locally