CodeBlanks Logo Icon CodeBlanks

useToggle

Learn to write the useToggle custom hook.

What is useToggle?

useToggle is a custom hook that flips a boolean value. It holds a useState inside and returns a toggle function. When toggle is called, the value flips from true to false or back.

Common uses: open/close a menu, show/hide a modal, expand/collapse a detail. You start it with const [isOpen, toggle] = useToggle(false). You pass toggle to a button's onPress; each press flips the value. This pattern shortens code and keeps it consistent.

Using useToggle

When you call useToggle in a component you destructure it. You write const [isVisible, toggle] = useToggle(false); isVisible is the state, toggle is the function that flips it.

On a button press you call toggle; isVisible flips each time. If it was open it closes, if it was closed it opens. You can pass true instead of false as the initial value; it only sets the start state. useToggle collects the repeated setOpen(!open) pattern into one hook.

Practice Write useToggle

Write the useToggle custom hook. Hold a value state with useState (initial value is the initial parameter). The toggle function sets !value. The hook returns [value, toggle].

Starter code

App.js
// Import useState

// Write the useToggle custom hook
// Start value state with initial
// toggle sets !value
// Return [value, toggle]

Sample solution

App.js
import { useState } from "react";

function useToggle(initial) {
  const [value, setValue] = useState(initial);
  const toggle = () => setValue(!value);
  return [value, toggle];
}

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Complete the toggle logic

Question
function useToggle(initial) {
  const [value, setValue] = useState(initial);
  const toggle = () => setValue(____);
  return [value, toggle];
}
Answer
function useToggle(initial) {
  const [value, setValue] = useState(initial);
  const toggle = () => setValue(!value);
  return [value, toggle];
}

Explanation: answer: !value. toggle flips the value.

2 What does useToggle return?

App.js
const [isOpen, toggle] = useToggle(false);
  • Only the value
  • Only the function
  • Nothing
  • The value and a toggle function Correct answer

Explanation: useToggle returns the value and the toggle function.

3 Match each piece to its role

Term Meaning
useToggle Boolean on/off
useState Holds state
toggle Flips the value
initial Starting value

All lessons in Intermediate