Skip to content
  • Homepage
  • HTML
  • CSS
  • Symfony
  • PHP
  • How to
  • Contact
  • Donate

Teach Developer

Articles, Guides & Tips

How to Make Toggles With React Hooks

Home  »  React • JavaScript   »   How to Make Toggles With React Hooks
Posted on January 3, 2023January 3, 2023
799

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

import { useState } from 'react'

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

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

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:

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>
    );
};
React, JavaScript

Post navigation

Previous Post: How to Get Environment Variables in Laravel ReactJS
Next Post: How to Define Global Variables for Twig Templates in Symfony 6

Related Posts

  • How do sum values from an array of key-value pairs in JavaScript?
  • Understanding State in React Components
  • Difference between var, let, and const in JavaScript
  • How to Use useLocation Hook in React Router DOM V6
  • How to use setTimeout and setInterval methods in JavaScript
  • How to Get Environment Variables in Laravel ReactJS

Categories

  • Codeigniter (3)
  • CSS (11)
  • eCommerce (1)
  • Framework (1)
  • Git (3)
  • How to (43)
  • HTML (5)
  • JavaScript (15)
  • Jquery (7)
  • Laravel (1)
  • Linux (4)
  • Magento-2 (1)
  • Node js (4)
  • Others (2)
  • PHP (11)
  • React (13)
  • Server (1)
  • SSH (3)
  • Symfony (6)
  • Tips (16)
  • Top Tutorials (10)
  • Ubuntu (3)
  • Vue (1)
  • Wordpress (7)

Latest Posts

  • What is SSH in Linux?
  • How to Delete Files in Ubuntu Command Line
  • How to Deploy a React application on a cPanel
  • How to use events listeners and Event Subscriber in Symfony
  • How to Convert PHP CSV to JSON

WEEKLY TAGS

AJAX (1) Codeigniter (1) Javascript (11) JQuery (1) PHP (16) Programming (1) React (3) Symfony (1)

Random Post

How to check PHP version using the command line
How to use events listeners and Event Subscriber in Symfony
Common Mistakes with Conditionals
How to install Git on Linux
How to clear your cache in npm

Quick Navigation

  • About
  • Contact
  • Privacy Policy

© Teach Developer 2021. All rights reserved