A Custom Hook is a JavaScript function that allows us to reuse stateful logic (React Hooks logic) in multiple components.
Create a counter Custom Hook.
import { useState } from "react";
function useCounter() {
const [count, setCount] = useState(0);
const increment = () => {
setCount(count + 1);
};
const decrement = () => {
setCount(count - 1);
};
return { count, increment, decrement };
}
export default useCounter;
Use the Custom Hook in App.jsx:
import React from "react";
import useCounter from "./useCounter";
function App() {
const { count, increment, decrement } = useCounter();
return (
<div>
<h2>Counter: {count}</h2>
<button onClick={increment}>Increment</button>
<button onClick={decrement}>Decrement</button>
</div>
);
}
export default App;
Examples:
- useCounter()
- useFetch()
- useLocalStorage()
- useWindowSize()
Top comments (0)