DEV Community

Ramesh Vishnoi
Ramesh Vishnoi

Posted on • Updated on

Write your custom Hook

This is a step-by-step guide on how to create custom hooks in React. Custom hooks are a fantastic way to encapsulate logic and functionality that can be reused across multiple components in your application.

Creating custom hooks can make your code much more efficient, reusable, and easier to read. The article does a great job of breaking down the process into simple steps that anyone can follow, making it an excellent resource for React developers of all levels.

If you have common code used across multiple components. You must be wondering why need hook in the first place, why not use good old functions which are available from in Vanilla JS.

With Hooks you can listen to events, such as is device online or offline (very useful for mobile apps), listen for window resize events or create a hook which communicates between webview.

Some of rules for writing hooks.

  1. Your hook name should shart with use. React have naming convention which it uses to differentiate between Components and Hooks. For ex - Component name should always start with Capital letter.

  2. Hooks only work in Functional components.

  3. Hooks do not work conditionally. For ex - you cannot put hook inside if else block.

  4. Hooks re-render with components. Every time, props or state changes, it re-renders hooks l.e hook will have latest props and state value.

Lets build a hook which tracks cursor and returns its x and y coordinates.

Step 1: Declare hook
import { useState, useEffect } from 'react';

function useTrackCursor() {
  const [coord, setCoord] = useState({
    x: 0,
    y: 0
  })

  useEffect(() => {
    function handleResize(event) {
      setCoord({
        x: event.pageX,
        y: event.pageY,
      });
    }

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

  return coord;
}

export default useTrackCursor;
Enter fullscreen mode Exit fullscreen mode
Step 2 : Consume Hook in components.
import useTrackCursor from "../hooks/trackCursor";

const HomeScreen = () => {
    const {x, y} = useTrackCursor();
    return (
        <div className="App">
            <header className="App-header">
                <p> X Co-ordinate : {x}</p>
                <p> Y Co-ordinate : {y}</p>
            </header>
        </div>
    )
}

export default HomeScreen;
Enter fullscreen mode Exit fullscreen mode

Hooks let you reuse common stateful logic between different components.

If you're interested in learning more about React, React Native and JS, check out my Linkedin profile here. And feel free to share it with anyone who might find it helpful!

Happy coding!

Top comments (0)