Skip to content

Instantly share code, notes, and snippets.

@Wintus
Last active July 30, 2021 11:56
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Wintus/86a635bdd038242a5752bfe4e7db2064 to your computer and use it in GitHub Desktop.
Save Wintus/86a635bdd038242a5752bfe4e7db2064 to your computer and use it in GitHub Desktop.
React Custom Hooks
import React from "react";
import { useInterval } from "./useInterval";
const now = () => new Date();
export const Clock = () => {
const date = useInterval(1000, now, now);
return (
<div>
<h1>Clock</h1>
<h2>{date.toLocaleString()}</h2>
</div>
);
};
export default Clock;
import { useState, useEffect } from "react";
export function useInterval<T>(
interval: number,
init: T | () => T,
update: (prev: T) => T
): T {
const [state, setState] = useState(init);
useEffect(() => {
const tick = () => setState(update);
const id = setInterval(tick, interval);
return () => clearInterval(id);
}, [interval, update]);
return state;
}
import { useCallback, useState } from "react";
export const useRerender = () => {
const [, setDummy] = useState();
const forceUpdate = useCallback(() => {
const newRef = {};
setDummy(newRef);
}, []);
return { forceUpdate };
};
import { useState, useEffect } from "react";
export const useTimeout = (initial, fallback, timeout) => {
const [state, setState] = useState(initial);
useEffect(() => {
const timer = setTimeout(() => setState(fallback), timeout);
return () => clearTimeout(timer);
}, [state, fallback, timeout]);
return [state, setState];
};
import { useEffect, useRef } from "react";
const useUnmounted = () => {
const unmounted = useRef(false);
useEffect(() => {
// no-op on mounted
return () => {
unmounted.current = true;
};
}, []); // once at the first mount
return unmounted;
};
@Wintus
Copy link
Author

Wintus commented Sep 6, 2019

@Wintus
Copy link
Author

Wintus commented Feb 21, 2020

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment