Simple boolean state toggle hook
Quick Answer
useToggle wraps useState with a memoized toggle function so you get a stable boolean and a one-call flip function — no !prev pattern needed, no accidental new function references on every render.
1import { useState, useCallback } from 'react';
2
3function useToggle(initialState: boolean = false): [boolean, () => void] {
4 const [state, setState] = useState(initialState);
5 const toggle = useCallback(() => setState(state => !state), []);
6 return [state, toggle];
7}useToggle wraps a boolean useState with a memoized toggle function so you never accidentally create a new function reference on every render. It is the go-to hook for any show/hide, open/close, or on/off UI pattern.
useToggle gives you a stable toggle function reference via useCallback and saves writing the !prev pattern every time.
The basic version only toggles. Return setState alongside toggle if you need to set a specific value.
This free typescript code snippet for usetoggle hook is production-ready and copy-paste friendly. Whether you are building a web app, API, or frontend interface, this beginner-level example will help you implement usetoggle hook quickly and correctly.
All snippets in the Snippetly library follow typescript best practices and are tested for real-world use. You can adapt this code to work with React, Vue, Node.js, or any project that uses typescript.
Organise your team's code snippets with Snippetly. Share knowledge and boost productivity across your organisation.