Discover how a simple custom hook can save you hours of repetitive coding!
Why custom hooks are used in React - The Real Reasons
Imagine you have several React components that need to share the same logic, like fetching data or handling form inputs. You copy and paste the same code into each component.
Copying code everywhere makes your app hard to maintain. If you find a bug or want to improve the logic, you must update every place manually. This leads to mistakes and wasted time.
Custom hooks let you put shared logic into one place. Then, any component can use that logic by calling the custom hook. This keeps your code clean, reusable, and easy to update.
import { useState } from 'react'; function ComponentA() { const [count, setCount] = useState(0); // duplicated logic here } function ComponentB() { const [count, setCount] = useState(0); // duplicated logic here }
import { useState } from 'react'; function useCounter() { const [count, setCount] = useState(0); return { count, setCount }; } function ComponentA() { const { count, setCount } = useCounter(); } function ComponentB() { const { count, setCount } = useCounter(); }
Custom hooks enable easy sharing and reuse of logic across components, making your app simpler and faster to build.
Think of a shopping app where multiple pages need to track the user's cart state. A custom hook can manage the cart logic once, and all pages can use it without repeating code.
Copy-pasting logic causes bugs and hard maintenance.
Custom hooks let you share logic cleanly across components.
This leads to reusable, easier-to-update code.
Practice
Solution
Step 1: Understand the purpose of hooks
Hooks in React let you use state and other React features without writing a class.Step 2: Identify why custom hooks are made
Custom hooks let you reuse stateful logic easily across different components, avoiding repetition.Final Answer:
To reuse stateful logic across multiple components -> Option AQuick Check:
Custom hooks = reuse logic [OK]
- Thinking custom hooks are for styling
- Believing custom hooks replace components
- Confusing hooks with HTML syntax
Solution
Step 1: Recall React naming conventions for hooks
React requires custom hooks to start with the word 'use' to identify them as hooks.Step 2: Check each option
Only 'useFetchData' starts with 'use', following React's convention.Final Answer:
useFetchData -> Option AQuick Check:
Custom hook names start with 'use' [OK]
- Not starting the name with 'use'
- Using camel case without 'use' prefix
- Confusing component names with hook names
function useCounter() {
const [count, setCount] = React.useState(0);
React.useEffect(() => {
const timer = setInterval(() => setCount(c => c + 1), 1000);
return () => clearInterval(timer);
}, []);
return count;
}
function Counter() {
const count = useCounter();
return {count};
}Solution
Step 1: Analyze the custom hook useCounter
It initializes count to 0 and sets up a timer to increase count by 1 every second.Step 2: Understand the component output
The Counter component uses useCounter and displays the count, which updates every second.Final Answer:
A number that increases by 1 every second starting from 0 -> Option CQuick Check:
useCounter returns incrementing count [OK]
- Thinking count stays 0 forever
- Believing hooks can't be used in functions
- Assuming output is a string, not a number
function useData() {
const [data, setData] = React.useState(null);
fetch('https://api.example.com/data')
.then(res => res.json())
.then(json => setData(json));
return data;
}
function App() {
const data = useData();
return <div>{JSON.stringify(data)}</div>;
}Solution
Step 1: Check where fetch is called in useData
fetch is called directly inside the hook body, causing it to run on every render, leading to infinite loops.Step 2: Correct usage with useEffect
fetch should be inside a useEffect with an empty dependency array to run only once on mount.Final Answer:
The fetch call should be inside useEffect to avoid infinite loops -> Option BQuick Check:
Side effects go inside useEffect [OK]
- Calling fetch directly in hook body
- Misusing useState instead of useEffect
- Thinking hooks can't return values
Solution
Step 1: Understand the need for reusable logic
Fetching data and managing loading state is stateful logic that can be reused with a custom hook.Step 2: Evaluate options for sharing logic
Creating a custom hook that returns data and loading state allows multiple components to share this logic cleanly.Final Answer:
Create a custom hook that fetches user data and returns both data and loading state -> Option DQuick Check:
Custom hooks share stateful logic best [OK]
- Duplicating fetch code in every component
- Using class components instead of hooks
- Using global variables that break React's state flow
Ready to prove it?
Pass the test and this pattern moves unknown
