Why Custom Hooks Are Used in React
📖 Scenario: You are building a React app that needs to reuse some logic for fetching data from an API. Instead of repeating the same code in multiple components, you want to create a custom hook to keep your code clean and easy to maintain.
🎯 Goal: Build a simple custom hook called useFetchData that fetches data from a URL and returns the data and loading state. Then use this hook in a component to display the fetched data.
📋 What You'll Learn
Create a custom hook named
useFetchData that accepts a url parameter.Inside the hook, use
useState to store data and loading states.Use
useEffect to fetch data from the given url when the hook runs.Return
data and loading from the hook.Create a functional component named
DataDisplay that uses useFetchData to fetch and show data.Show a loading message while data is being fetched.
Display the fetched data once loading is complete.
💡 Why This Matters
🌍 Real World
Custom hooks are used in real React apps to share logic like data fetching, form handling, or animations across many components without repeating code.
💼 Career
Knowing how to write and use custom hooks is important for React developers to build maintainable and scalable applications efficiently.
Progress0 / 4 steps