Hone logo
Hone
Problems

Create a Reusable useBoolean Hook in React with TypeScript

The useBoolean hook is a common utility in React applications, providing a convenient way to manage a boolean state value along with functions to toggle, set to true, and set to false. This challenge asks you to implement this hook from scratch, ensuring type safety with TypeScript. Building this hook reinforces understanding of React hooks and state management.

Problem Description

You need to create a custom React hook called useBoolean. This hook should accept an initial boolean value as an argument and return an object containing:

  • value: The current boolean value.
  • setTrue: A function to set the boolean value to true.
  • setFalse: A function to set the boolean value to false.
  • toggle: A function to toggle the boolean value (if it's true, set it to false, and vice versa).

The hook should manage its state internally using useState. The returned functions should update the state correctly and trigger re-renders.

Key Requirements:

  • The hook must be written in TypeScript.
  • The initial value should be optional, defaulting to false if not provided.
  • The returned object should have the specified properties with the correct types.
  • The functions should update the state and trigger re-renders.

Expected Behavior:

When the component using useBoolean initially renders, the value should reflect the initial value passed to the hook (or false if no initial value is provided). Calling setTrue, setFalse, or toggle should update the value accordingly and cause the component to re-render.

Edge Cases to Consider:

  • Initial value is true.
  • Initial value is false.
  • No initial value is provided.
  • Repeated calls to toggle should correctly alternate the boolean value.

Examples

Example 1:

Input:  Initial value: true
Output: { value: true, setTrue: Function, setFalse: Function, toggle: Function }
Explanation: The hook initializes with the value `true`.

Example 2:

Input: Initial value: false
Output: { value: false, setTrue: Function, setFalse: Function, toggle: Function }
Explanation: The hook initializes with the value `false`.

Example 3:

Input: No initial value provided
Output: { value: false, setTrue: Function, setFalse: Function, toggle: Function }
Explanation: The hook initializes with the default value `false`.

Constraints

  • The hook must be implemented using the useState hook.
  • The code must be valid TypeScript.
  • The hook should be reusable in any functional React component.
  • The returned functions should not accept any arguments.

Notes

  • Think about how to use useState to manage the boolean state.
  • Consider the types of the returned functions and the value property.
  • This is a good exercise to understand how to create custom hooks in React.
  • Focus on clarity and readability of your code.
Loading editor...
typescript