Skip to content

Instantly share code, notes, and snippets.

@Wintus

Wintus/Clock.tsx

Last active Feb 21, 2020
Embed
What would you like to do?
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

This comment has been minimized.

Copy link
Owner Author

@Wintus Wintus commented Sep 6, 2019

@Wintus

This comment has been minimized.

Copy link
Owner Author

@Wintus Wintus commented Feb 21, 2020

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