When you have component logic that needs to be used by multiple components, you can extract that logic into a Custom Hook.
React Frontend Framework
React Tutorial
Advertisement
Google AdSense Slot (LEADERBOARD)
Automated High-CTR Ad Rail • Set Publisher ID in config/adsense.php
Reusability
9 min read
•
Chapter 26 of 26
React Custom Hooks
Extract reusable component logic into custom JavaScript functions whose names start with "use".
Example
<!DOCTYPE html>
<html>
<head>
<script src="https://unpkg.com/react@18/umd/react.development.js"></script>
<script src="https://unpkg.com/react-dom@18/umd/react-dom.development.js"></script>
<script src="https://unpkg.com/@babel/standalone/babel.min.js"></script>
</head>
<body style="font-family:sans-serif;padding:20px;">
<div id="root"></div>
<script type="text/babel">
function useToggle(initialValue = false) {
const [value, setValue] = React.useState(initialValue);
const toggle = () => setValue(v => !v);
return [value, toggle];
}
function App() {
const [isOn, toggleIsOn] = useToggle(false);
return (
<div>
<h3>Custom useToggle Hook</h3>
<p>Status: {isOn ? "🟢 ON" : "🔴 OFF"}</p>
<button onClick={toggleIsOn}>Toggle Switch</button>
</div>
);
}
ReactDOM.createRoot(document.getElementById("root")).render(<App />);
</script>
</body>
</html>
Try it Yourself >>
Opens live sandboxed code editor
Advertisement
Google AdSense Slot (IN-ARTICLE)
Automated High-CTR Ad Rail • Set Publisher ID in config/adsense.php
Community Q&A & Discussion
Verified
No questions yet. Be the first to start the discussion!