HooneyLog

Basic and Useful React Custom Hooks

프로필 이미지

Seunghoon Shin

2022년 7월 27일 12:46

I think these are super useful that can be used at most of projects.

useToggle

import { useState } from "react";

const useToggle = (deafaultValue: boolean): [boolean, () => void] => {
  const [state, setState] = useState(deafaultValue);

  const toggle = () => {
    setState((prev) => !prev);
  };

  return [state, toggle];
};

export default useToggle;

This hook can be super useful at the situation of modal or something to keep changing boolean state.

UseTimeOut

import { useCallback, useEffect, useRef } from "react";

const useTimeout = (callback: () => void, delay: number) => {
  const timeoutRef = useRef<number>();
  const callbackRef = useRef<() => void>(callback);

  useEffect(() => {
    callbackRef.current = callback;
  }, [callback]);

  const set = useCallback(() => {
    if (!callbackRef.current) return;
    timeoutRef.current = setTimeout(callbackRef.current, delay);
  }, [delay]);

  const clear = useCallback(() => {
    clearTimeout(timeoutRef.current);
  }, []);

  const reset = useCallback(() => {
    clear();
    set();
  }, [clear, set]);

  useEffect(() => {
    set();
    return clear;
  }, [delay, set, clear]);

  return { reset, clear };
};

export default useTimeout;

This hook can be used when you want to execute a function after some time.

It is literally used for “setTimeout”, which is a pure javascript method.

and I also like that not making a code for “clearTimeout” every time I use setTimeout by using this hook.

UseDebounce

import { useEffect } from "react";
import useTimeout from "./useTimout";

const useDebounce = (
  callback: () => void,
  delay: number,
  dependencies: any[]
) => {
  const { reset, clear } = useTimeout(callback, delay);

  useEffect(reset, [...dependencies]);

  // * 첫 렌더때 클리어를 해줘야 처음에 콜백이 실행이 안됨.
  useEffect(clear, []);
};

export default useDebounce;

This hook is about having a delay time until you finish your event. It means nothing happens even if you keep doing something. I mean when you want to execute a function after a delay time after you finish an event. just giving a callback param, delay time, and dependencies. It should be good for the app performance.

useUpdateEffect

import { useEffect, useRef } from "react";

const useUpdateEffect = (callback: () => void, dependencies: any[]) => {
  const firstRender = useRef<boolean>(true);

  useEffect(() => {
    if (firstRender.current) {
      firstRender.current = false;
      return;
    }

    return callback();
  }, dependencies);
};

export default useUpdateEffect;

From time to time, you wouldn’t want run code on initial render using “useEffect”. you can achieve it by using this hook. just don’t initial render by using boolean useRef. Reallocate after initial render and execute callback function.