0
0
Reactframework~30 mins

Reusing logic with hooks in React - Mini Project: Build & Apply

Choose your learning style9 modes available
Reusing Logic with Hooks in React
📖 Scenario: You are building a simple React app that shows a counter. You want to reuse the counting logic in multiple places without repeating code.
🎯 Goal: Create a custom hook called useCounter that manages a counter value and a function to increase it. Then use this hook inside a functional component to display the count and a button to increase it.
📋 What You'll Learn
Create a custom hook named useCounter that returns a count state and an increment function.
Initialize the count state to 0 inside the hook.
Create a functional component named CounterDisplay that uses the useCounter hook.
Render the current count and a button labeled Increase inside CounterDisplay.
Clicking the button should increase the count by 1.
💡 Why This Matters
🌍 Real World
Custom hooks help you reuse logic like counters, form handling, or data fetching across many components without repeating code.
💼 Career
Understanding custom hooks is essential for React developers to write clean, maintainable, and reusable code in real projects.
Progress0 / 4 steps
1
Create the custom hook useCounter with initial count
Create a custom hook named useCounter that uses useState to create a state variable called count initialized to 0.
React
Need a hint?

Use useState(0) inside useCounter to create count and setCount.

2
Add an increment function inside useCounter
Inside the useCounter hook, create a function called increment that increases count by 1 using setCount. Return increment along with count from the hook.
React
Need a hint?

Define increment as a function that calls setCount(count + 1). Return it from the hook.

3
Create CounterDisplay component using useCounter
Create a functional component named CounterDisplay. Inside it, call the useCounter hook to get count and increment. Render a <div> with a <p> showing the text Count: {count} and a <button> with the label Increase that calls increment when clicked.
React
Need a hint?

Use object destructuring to get count and increment from useCounter(). Render them inside JSX.

4
Export CounterDisplay as default export
Add a default export statement for the CounterDisplay component at the end of the file.
React
Need a hint?

Use export default CounterDisplay; to export the component.