Sorting With useMemo
ReactJS
Medium
6 views
Problem Description
Sort a list only when sort options change, not on every render.
Output Format
Render a React component.
Constraints
Use useMemo for sorting and avoid mutating the original array.
Official Solution
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>
);
}
Solutions (0)
No solutions submitted yet. Be the first!
No comments yet. Start the discussion!