ReactJS Program to Memoized Presentational Component with Explanation
ReactJS
Hard
Performance & Patterns
19 views
1 min read
85 words
This problem helps you practice core ReactJS fundamentals in a practical way. It builds intuition around component, react, presentational. Let’s break it down step by step so you can implement it confidently.
Problem Statement
Create a presentational component and wrap it with React.memo.
Input Format
No input.
Output Format
Render a React component.
Constraints
Avoid re-rendering when props do not change.
Code Solution
This explanation is written for learning purposes and to help beginners understand the concept clearly.
import React, { useState } from 'react';
const TopicChip = React.memo(function TopicChip({ name }) {
return <span style={{ padding: '8px 10px', border: '1px solid #ddd', borderRadius: 999 }}>{name}</span>;
});
export default function App() {
const [count, setCount] = useState(0);
return (
<div style={{ padding: 16 }}>
<div style={{ display: 'flex', gap: 10 }}>
<TopicChip name='HTML' />
<TopicChip name='CSS' />
<TopicChip name='React' />
</div>
<button type='button' onClick={() => setCount((c) => c + 1)} style={{ marginTop: 12, padding: '10px 14px', borderRadius: 12, border: 0, background: '#0b5', color: '#fff' }}>
Clicked {count}
</button>
</div>
);
}
Output Example
No sample I/O is provided for this question.
Common Mistakes
- Misreading input/output format.
- Not handling constraints and edge cases.
- Off-by-one errors in loops.
- Forgetting to reset variables between test cases (if any).
Solution Guide
Problem
Create a presentational component and wrap it with React.memo.
Input / Output
Output
Render a React component.
Constraints
Avoid re-rendering when props do not change.
Details
Common Mistakes
- Misreading input/output format.
- Not handling constraints and edge cases.
- Off-by-one errors in loops.
- Forgetting to reset variables between test cases (if any).
Official Solution
import React, { useState } from 'react';
const TopicChip = React.memo(function TopicChip({ name }) {
return <span style={{ padding: '8px 10px', border: '1px solid #ddd', borderRadius: 999 }}>{name}</span>;
});
export default function App() {
const [count, setCount] = useState(0);
return (
<div style={{ padding: 16 }}>
<div style={{ display: 'flex', gap: 10 }}>
<TopicChip name='HTML' />
<TopicChip name='CSS' />
<TopicChip name='React' />
</div>
<button type='button' onClick={() => setCount((c) => c + 1)} style={{ marginTop: 12, padding: '10px 14px', borderRadius: 12, border: 0, background: '#0b5', color: '#fff' }}>
Clicked {count}
</button>
</div>
);
}
Solutions (0)
No solutions submitted yet. Be the first!