DEV Community

Ramesh Vishnoi
Ramesh Vishnoi

Posted on • Edited on

1

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!

SurveyJS custom survey software

Build Your Own Forms without Manual Coding

SurveyJS UI libraries let you build a JSON-based form management system that integrates with any backend, giving you full control over your data with no user limits. Includes support for custom question types, skip logic, an integrated CSS editor, PDF export, real-time analytics, and more.

Learn more

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay