The code in the function App uses a toggler function to change the text on a button from "Toggled" to "Click to Toggle". The toggler function is implemented as a function that takes two arguments: an initial state and a callback. The state argument is a reference to an object that remembers the current state of the toggle. The callback is called when the state changes, and it sets the state to the opposite of the previous state.

    Library: react

    import { useCallback, useState } from 'react';
    // Usage
    function App() {
      // Call the hook which returns, current value and the toggler function
      const [isTextChanged, setIsTextChanged] = useToggle();
      return (
        <button onClick={setIsTextChanged}>{isTextChanged ? 'Toggled' : 'Click to Toggle'}</button>
    // Hook
    // Parameter is the boolean, with default "false" value
    const useToggle = (initialState = false) => {
      // Initialize the state
      const [state, setState] = useState(initialState);
      // Define and memorize toggler function in case we pass down the component,
      // This function change the boolean value to it's opposite value
      const toggle = useCallback(() => setState(state => !state), []);
      return [state, toggle]
    View in TypeScript
    Codiga Logo
    Codiga Hub
    • Rulesets
    • Playground
    • Snippets
    • Cookbooks
    soc-2 icon

    We are SOC-2 Compliance Certified

    G2 high performer medal

    Codiga – All rights reserved 2022.