0
0
Reactframework~30 mins

Why custom hooks are used in React - See It in Action

Choose your learning style9 modes available
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
1
Set up state variables inside the custom hook
Create a custom hook called useFetchData that takes a url parameter. Inside it, use useState to create two state variables: data initialized to null and loading initialized to true.
React
Need a hint?

Remember to import useState and useEffect from React. Start by creating the function and the two state variables.

2
Add useEffect to fetch data from the URL
Inside the useFetchData hook, add a useEffect that runs when the url changes. Inside it, fetch data from the url, convert the response to JSON, then update data with the result and set loading to false.
React
Need a hint?

Use useEffect with url as a dependency. Use fetch to get data, then update states inside the promise chain.

3
Return data and loading from the custom hook
Complete the useFetchData hook by returning an object with data and loading properties.
React
Need a hint?

Return an object with the two state variables so components can use them.

4
Use the custom hook in a component to display data
Create a functional component called DataDisplay. Inside it, call useFetchData with the URL 'https://jsonplaceholder.typicode.com/todos/1'. If loading is true, return a <p> with text Loading.... Otherwise, display the JSON stringified data inside a <pre> tag.
React
Need a hint?

Use the custom hook inside the component. Show loading text while loading is true, then show the data formatted as JSON.