0
0
Reactframework~30 mins

React.memo usage - Mini Project: Build & Apply

Choose your learning style9 modes available
Optimize a React Counter with React.memo
📖 Scenario: You are building a simple React app with two counters. One counter updates frequently, and the other does not. To improve performance, you want to prevent unnecessary re-rendering of the counter that does not change.
🎯 Goal: Build two counter components in React. Use React.memo to optimize the component that does not need to re-render when the other counter changes.
📋 What You'll Learn
Create two functional components: CounterA and CounterB
Use useState to manage separate counts for each counter
Wrap CounterB with React.memo to prevent unnecessary re-renders
Add buttons to increment each counter separately
💡 Why This Matters
🌍 Real World
React.memo helps improve app performance by skipping re-renders of components when their inputs (props) have not changed, useful in apps with many components or frequent updates.
💼 Career
Understanding React.memo is important for frontend developers to write efficient React applications and optimize user experience.
Progress0 / 4 steps
1
Set up two counters with state
Create a React functional component called App. Inside it, use useState to create two state variables: countA and countB, both starting at 0.
React
Need a hint?

Use const [countA, setCountA] = useState(0) and similarly for countB.

2
Create two counter components
Create two functional components called CounterA and CounterB. Each should accept count and onIncrement props. Render the count inside a <div> and a button that calls onIncrement when clicked.
React
Need a hint?

Return a <div> with a <p> showing the count and a button that calls onIncrement.

3
Use React.memo to optimize CounterB
Wrap the CounterB component with React.memo to prevent it from re-rendering when its props do not change.
React
Need a hint?

Use const CounterB = React.memo(function CounterB(props) { ... }).

4
Render counters and add increment handlers
Inside the App component, render CounterA and CounterB. Pass countA and setCountA as count and onIncrement props to CounterA. Pass countB and setCountB similarly to CounterB. For onIncrement, pass a function that increases the count by 1.
React
Need a hint?

Render both counters and pass increment functions that add 1 to the current count.