How to Make Toggles With React Hooks

How to Make Toggles With React Hooks

Ferenc Almasi β€’ Last updated 2021 February 08 β€’ Read time 2 min read
  • twitter
  • facebook
React

To toggle between a boolean flag in React, you can use the below custom hook that uses setState internally:

Copied to clipboard! Playground
import { useState } from 'react'

const useToggle = initialState => {
    const [state, setState] = useState(initialState || false);

    return [state, () => setState(!state)];
};
useToggle.js

Since the function returns an array, with a state and a callback function, you can use it in your component, just like you would for other built-in React hooks, like so:

Copied to clipboard! Playground
import React, { useState } from 'react'
import useToggle from 'useToggle'

const toggleComponent = () => {
    const [lightsOn, toggleLights] = useToggle();
    const [isVisible, toggleSidebar] = useToggle();

    return (
        <React.Fragment>
            <button onClick={toggleLights}>{lightsOn ? '🌞' : 'πŸŒ’'}</button>;
            <button onClick={toggleSidebar}>Toggle sidebar</button>;
            <Sidebar visible={isVisible} />
        </React.Fragment>
    );
};
useToggle.js

If you would like to see it in action, give it a try on Codesandbox

Try the hook on codesandbox
How to Make Toggles With React Hooks
If you would like to see more Webtips, follow @flowforfrank

If you are interested in reading more about React hooks, see more examples for custom hooks or just learn about the basics, make sure to check out the article below.

All You Need to Know About React Hooks
  • twitter
  • facebook
React
Did you find this page helpful?
πŸ“š More Webtips
Frontend Course Dashboard
Master the Art of Frontend
  • check Access 100+ interactive lessons
  • check Unlimited access to hundreds of tutorials
  • check Prepare for technical interviews
Become a Pro

Courses

Recommended

This site uses cookies We use cookies to understand visitors and create a better experience for you. By clicking on "Accept", you accept its use. To find out more, please see our privacy policy.