React 05: Custom Hooks
Docs
Problem Statement
Solution
Custom Hook: Example One
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];
};Custom Hook: Example Two
Last updated