0
0
Reactframework~30 mins

useCallback hook in React - Mini Project: Build & Apply

Choose your learning style9 modes available
Using the useCallback Hook in React
📖 Scenario: You are building a simple React app that counts clicks on two buttons. You want to make sure the click handler functions do not get recreated unnecessarily to keep your app efficient.
🎯 Goal: Build a React component with two buttons that share a click handler function memoized using the useCallback hook.
📋 What You'll Learn
Create a state variable count initialized to 0
Create a function handleClick that increases count by 1
Use the useCallback hook to memoize handleClick with count as dependency
Render two buttons that both use handleClick as their onClick handler
Display the current count value in a <p> tag
💡 Why This Matters
🌍 Real World
Using useCallback helps keep React apps fast by preventing unnecessary function recreations, especially when passing functions to child components.
💼 Career
Understanding useCallback is important for React developers to write efficient, maintainable code and improve app performance.
Progress0 / 4 steps
1
Set up state with useState
Import useState from React and create a state variable called count initialized to 0 inside a functional component named ClickCounter.
React
Need a hint?

Use const [count, setCount] = useState(0); inside the component.

2
Create the click handler function
Inside the ClickCounter component, create a function called handleClick that calls setCount to increase count by 1.
React
Need a hint?

Define handleClick as a function that calls setCount(count + 1).

3
Memoize the click handler with useCallback
Import useCallback from React and wrap the handleClick function with useCallback, passing count as a dependency.
React
Need a hint?

Use const handleClick = useCallback(() => { setCount(count + 1); }, [count]);.

4
Render buttons and display count
Render two <button> elements inside the component. Both buttons should use handleClick as their onClick handler. Also render a <p> tag that shows the current count value.
React
Need a hint?

Use JSX to render two buttons with onClick={handleClick} and a paragraph showing Count: {count}.