React 05: Custom Hooks


Docs

https://react.dev/learn/reusing-logic-with-custom-hooks


Problem Statement

I want to reuse code logic that includes a React Hook i.e. useEffect() with call to a database.

Solution

Create a custom hook.


Custom Hook: Example One

useCounter.js :

import { useState, useEffect } from "react";

export const useCounter = (start = 0) => {
  const [counter, setCounter] = useState(start);

  useEffect(() => {           // useEffect so that it runs whenever counter changes
    if (counter % 2 == 0)) {
      alert("counter is even" + counter)
    } else {
      alert("counter is odd" + counter)
    }
  }, [counter]);

  // create an easy-to-use increment function
  const increment = () => {
    setCounter((counter) => counter + 1);
  };

  // return the counter value and the incrementer
  return [counter, increment];
};

App.js :


Custom Hook: Example Two

TBD: custom hooks on form ??

useFormInput.js :

App.js :

Last updated