Skip to content

Instantly share code, notes, and snippets.

@kitze
Last active March 3, 2020 09:35
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save kitze/fc136d8234e55c8b08df42636ac129d1 to your computer and use it in GitHub Desktop.
Save kitze/fc136d8234e55c8b08df42636ac129d1 to your computer and use it in GitHub Desktop.
React Advanced Hooks
import React, {useEffect, useState} from "react";
import { useEffect, useState } from "react";
export const useTimer = (initialValue = 0, duration = 1000, step = 1) => {
const [timer, setTimer] = useState(initialValue);
useEffect(() => {
const interval = setInterval(() => {
setTimer(timer => timer + step);
}, duration);
return () => clearInterval(interval);
}, [step, duration]);
return timer;
};
export const useNumber = (initialValue = 0) => {
const [value, setValue] = useState(initialValue);
const decrease = () => {
setValue(value - 1);
};
const increase = () => {
setValue(value + 1);
};
return {
value,
setValue,
increase,
decrease
};
};
export const useBoolean = (initialState = true) => {
const [value, setValue] = useState(initialState);
const toggle = () => {
setValue(!value);
};
const setTrue = () => {
setValue(true);
};
const setFalse = () => {
setValue(false);
};
return { value, setTrue, setFalse, setValue, toggle };
};
export const useInput = (initialState = "") => {
const [value, setValue] = useState(initialState);
const onChange = e => setValue(e.target.value);
const clear = () => setValue("");
const reset = () => setValue(initialState);
const isValid = value && value.trim() !== "";
const bind = {
value,
onChange
};
return {
bind,
setValue,
clear,
reset,
isValid
};
};
export const useLegacyState = initialState => {
const [state, setState] = useState(initialState);
const keepAndUpdateState = updateState => {
setState({
...state,
...updateState
});
};
return [state, keepAndUpdateState];
};
export const useDocumentTitle = title => {
useEffect(() => {
console.log("CALLING DOCUMENT EFFECT");
window.document.title = title;
}, [title]);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment