MeetCode - Programming Platform | MeetCode - Programming Solutions Platform

ReactJS Program to Sorting With useMemo with Explanation

ReactJS Medium Performance & Patterns 33 views
This problem helps you practice core ReactJS fundamentals in a practical way. It builds intuition around sorting, usememo, sort. Let’s break it down step by step so you can implement it confidently.
Back to Questions

Problem Statement

Sort a list only when sort options change, not on every render.

Input Format

No input.

Output Format

Render a React component.

Constraints

Use useMemo for sorting and avoid mutating the original array.

Code Solution

This explanation is written for learning purposes and to help beginners understand the concept clearly.
import React, { useMemo, useState } from 'react'; const base = [ { id: 1, title: 'meetcode arrays' }, { id: 2, title: 'meetcode hooks' }, { id: 3, title: 'meetcode forms' }, { id: 4, title: 'meetcode state' } ]; export default function App() { const [dir, setDir] = useState('asc'); const [ticks, setTicks] = useState(0); const sorted = useMemo(() => { const copy = [...base]; copy.sort((a, b) => a.title.localeCompare(b.title)); if (dir === 'desc') copy.reverse(); return copy; }, [dir]); return ( <div style={{ padding: 16, width: 520 }}> <h2 style={{ marginTop: 0 }}>Sort list</h2> <div style={{ display: 'flex', gap: 10 }}> <button type='button' onClick={() => setDir((d) => (d === 'asc' ? 'desc' : 'asc'))} style={{ padding: '10px 14px', borderRadius: 12, border: 0, background: '#0b5', color: '#fff' }}>Direction: {dir}</button> <button type='button' onClick={() => setTicks((t) => t + 1)} style={{ padding: '10px 14px', borderRadius: 12, border: '1px solid #ddd', background: '#fff' }}>Unrelated: {ticks}</button> </div> <ul style={{ marginTop: 12 }}> {sorted.map((x) => <li key={x.id}>{x.title}</li>)} </ul> </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