0
0
Reactframework~30 mins

Custom hook best practices in React - Mini Project: Build & Apply

Choose your learning style9 modes available
Custom Hook Best Practices in React
📖 Scenario: You are building a React app that fetches user data from an API. To keep your code clean and reusable, you want to create a custom hook that handles fetching and loading state.
🎯 Goal: Build a custom React hook called useUserData that fetches user data from a URL, manages loading state, and returns the data and loading status. Then use this hook in a functional component to display the user name or a loading message.
📋 What You'll Learn
Create a state variable to hold user data
Create a state variable to hold loading status
Use useEffect to fetch data from https://jsonplaceholder.typicode.com/users/1
Return the user data and loading status from the custom hook
Use the custom hook in a component to show loading or user name
💡 Why This Matters
🌍 Real World
Custom hooks help keep React code clean and reusable, especially for common tasks like data fetching.
💼 Career
Understanding custom hooks is essential for React developers to write maintainable and scalable applications.
Progress0 / 4 steps
1
Set up state variables in the custom hook
Create a custom hook called useUserData. Inside it, create a state variable called user initialized to null and a state variable called loading initialized to true using useState.
React
Need a hint?

Use useState(null) for user and useState(true) for loading.

2
Add useEffect to fetch user data
Inside the useUserData hook, add a useEffect that fetches data from https://jsonplaceholder.typicode.com/users/1. When the data is received, update user with the JSON response and set loading to false. Use an empty dependency array [] so it runs once.
React
Need a hint?

Use fetch inside useEffect and update states inside then.

3
Return user and loading from the custom hook
At the end of the useUserData hook, return an object with user and loading properties.
React
Need a hint?

Return an object with user and loading.

4
Use the custom hook in a component
Create a functional component called UserProfile. Inside it, call the useUserData hook to get user and loading. If loading is true, return a <p> with text "Loading...". Otherwise, return a <p> showing the user's name from user.name.
React
Need a hint?

Call the hook, check loading, and show user name inside a paragraph.