Example of useToggle() Custom hook in React.js

Example of useToggle() Custom hook in React.js

Here's how to make a useToggle hook in React, which lets you switch between two states (like true and false):

import { useState } from 'react';

const useToggle = (initialValue = false) => {
  const [value, setValue] = useState(initialValue);

  const toggleValue = () => {
    setValue((prevValue) => !prevValue);
  };

  return [value, toggleValue];
};

export default useToggle;

You can use this useToggle hook in your components to toggle between two states. Here's how you can use it:

import React from 'react';
import useToggle from './useToggle'; // Assuming you've placed the hook in a separate file

const MyComponent = () => {
  const [isToggled, toggle] = useToggle();

  return (
    <div>
      <h1>Toggle Example</h1>
      <button onClick={toggle}>
        {isToggled ? 'Turn off' : 'Turn on'}
      </button>
      {isToggled && <p>Toggle is on!</p>}
    </div>
  );
};

export default MyComponent;

In this example:

  • We create a component called MyComponent.

  • We use a hook called useToggle to manage a true/false state and a function to change it.

  • Clicking the button changes the true/false state.

  • If the state is true, we show a message saying the toggle is on.

The useToggle hook makes it easier to switch between two states in React components by removing the need for repetitive code. It helps in making the code more reusable and the components simpler to understand.