How create custom hook

In the next post you can check simple sample, of can create your own custom hook, please check this below, and if you want check working click here

import "./styles.css";
import { useState } from "react";

// Custom hook to manage the counter logic
const HookCounter = () => {
  // State for the counter
  const [cont, setCount] = useState(0);

  // Increment the counter by 1
  const inc = () => setCount(cont + 1);
  
  // Decrement the counter by 1
  const dec = () => setCount(cont - 1);
  
  // Return the current counter value and functions to modify it
  return [cont, inc, dec];
};

const Component = () => {
  // Using the custom HookCounter to get the current counter value and the increment and decrement functions
  const [counter, increment, decrement] = HookCounter(); 

  return (
    <div>
      // Button to increment the counter
      <button onClick={increment}>+1</button>
      <h2>{counter}</h2>
      // Button to decrement the counter
      <button onClick={decrement}>-1</button>
    </div>
  );
};

export default function App() {
  return (
    <div className="App">
      <h1>Hello CodeSandbox</h1>
      // Rendering the Component which includes the counter and the buttons
      <Component />
    </div>
  );
}

Post Comment