Skip to content

Instantly share code, notes, and snippets.

@codemile
Created June 29, 2021 18:44
Show Gist options
  • Save codemile/bb79b4a603013f060540ca65b693a37a to your computer and use it in GitHub Desktop.
Save codemile/bb79b4a603013f060540ca65b693a37a to your computer and use it in GitHub Desktop.
Hook that increments a counter every time useState() is changed.
import {useCallback, useState} from 'react';
export const useStateCount = <TType extends any>(initialState?: TType) => {
const [[count, value], setState] = useState([0, initialState]);
const setValue = useCallback(
(next: TType) => setState([count + 1, next]),
[count]
);
return [count, value, setValue];
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment