MeetCode - Programming Platform | MeetCode - Programming Solutions Platform

ReactJS Program to React.memo With Custom Compare with Explanation

ReactJS Hard Performance & Patterns 28 views
This problem helps you practice core ReactJS fundamentals in a practical way. It builds intuition around react, memo, custom. Let’s break it down step by step so you can implement it confidently.
Back to Questions

Problem Statement

Memoize rows so only the selected row re-renders when selection changes.

Input Format

No input.

Output Format

Render a React component.

Constraints

Use React.memo with a custom compare function.

Code Solution

This explanation is written for learning purposes and to help beginners understand the concept clearly.
import React, { memo, useCallback, useMemo, useState } from 'react'; const items = Array.from({ length: 600 }, (_, i) => ({ id: i + 1, name: 'meetcode item ' + (i + 1) })); const Row = memo( function Row({ item, selected, onSelect }) { return ( <button type='button' onClick={() => onSelect(item.id)} style={{ width: '100%', textAlign: 'left', padding: '8px 12px', borderRadius: 12, border: '1px solid ' + (selected ? '#0b5' : '#eee'), background: selected ? '#eafaf1' : '#fff', cursor: 'pointer' }} > {item.name} </button> ); }, (prev, next) => prev.item.id === next.item.id && prev.item.name === next.item.name && prev.selected === next.selected ); export default function App() { const [selectedId, setSelectedId] = useState(1); const onSelect = useCallback((id) => setSelectedId(id), []); const shown = useMemo(() => items.slice(0, 120), []); return ( <div style={{ padding: 16, width: 520 }}> <h2 style={{ marginTop: 0 }}>Memo rows</h2> <div style={{ color: '#555' }}>Selected: {selectedId}</div> <div style={{ marginTop: 10, display: 'grid', gap: 8, height: 300, overflow: 'auto' }}> {shown.map((item) => ( <Row key={item.id} item={item} selected={item.id === selectedId} onSelect={onSelect} /> ))} </div> </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).

Notes & Extra Practice

Solutions (0)

No solutions submitted yet. Be the first!

Prev Next