Memoized Row Component
ReactJS
Hard
6 views
Problem Description
Create a table where each row is memoized to avoid extra re-renders.
Output Format
Render a React component.
Constraints
Use React.memo for Row and pass stable props.
Official Solution
import React, { useMemo, useState } from 'react';
const Row = React.memo(function Row({ item }) {
return (
<tr>
<td style={{ border: '1px solid #ddd', padding: 8 }}>{item.id}</td>
<td style={{ border: '1px solid #ddd', padding: 8 }}>{item.title}</td>
</tr>
);
});
export default function App() {
const [count, setCount] = useState(0);
const data = useMemo(() => Array.from({ length: 12 }, (_, i) => ({ id: i + 1, title: 'meetcode item ' + (i + 1) })), []);
return (
<div style={{ padding: 16 }}>
<h2 style={{ marginTop: 0 }}>Memo rows</h2>
<button type='button' onClick={() => setCount((n) => n + 1)} style={{ padding: '8px 12px', borderRadius: 12, border: 0, background: '#0b5', color: '#fff' }}>Re-render ({count})</button>
<table style={{ marginTop: 12, borderCollapse: 'collapse', width: 520 }}>
<tbody>
{data.map((item) => <Row key={item.id} item={item} />)}
</tbody>
</table>
</div>
);
}
Solutions (0)
No solutions submitted yet. Be the first!
No comments yet. Start the discussion!