lodash
Lodash 工具庫
TL;DRLodash 提供大量 utility 函式(陣列 / 物件 / debounce / throttle / 深拷貝)。2026 年觀察:多數 method 已被 現代 JS 原生 API 取代(structuredClone / Array.from(new Set()) / 等),只在需要 debounce / throttle 等非原生功能時用。
正確 import(tree-shake 友善)
// ❌ 不推薦:整個包進來(~70KB gzipped)
import _ from 'lodash';
_.debounce(fn, 300);
// ✅ 推薦:單一 method
import debounce from 'lodash/debounce';
// ✅ 或 ESM 版本(原生 tree-shake)
import { debounce } from 'lodash-es';
lodash-es vs lodash/{method}:
lodash-es— ES Modules,Vite / Rollup 自動 tree-shakelodash/debounce— 手動指定單一 method,Webpack / 老 toolchain 也可以
都比 import _ from 'lodash' 小很多。
常用函式 + 原生替代
| Lodash | 用途 | 原生替代(2026) |
|---|---|---|
debounce | 防抖(搜尋框) | ❌ 沒原生 → Lodash 仍最佳 |
throttle | 節流(滾動) | ❌ 沒原生 → Lodash 仍最佳 |
cloneDeep | 深拷貝 | ✅ structuredClone(obj) |
isEqual | 深比較 | ❌ 沒原生 → Lodash 仍可 |
get | 安全取值 | ✅ obj?.a?.b?.c ?? default |
groupBy | 分組 | ✅ Object.groupBy(arr, fn) (ES2024) |
uniqBy | 去重 | ⚠️ Array.from(new Map(arr.map(x => [x.id, x])).values()) |
flatten | 攤平 | ✅ arr.flat() |
flattenDeep | 完全攤平 | ✅ arr.flat(Infinity) |
chunk | 切塊 | ❌ 沒原生 → Lodash |
merge | 深合併 | ❌ 沒原生( Object.assign 是淺合併) |
2026 年保留 Lodash 的理由
- debounce / throttle(原生沒有)
- isEqual(深比較,原生
===是 reference 相等)- merge(深合併)
- chunk / partition / countBy / orderBy / sortBy 等 array helpers
純粹的 cloneDeep / get / flatten / groupBy / uniqBy 都已有原生 / 簡單寫法。
debounce 範例(最常用)
import debounce from 'lodash/debounce';
// 搜尋框 debounce
const handleSearch = debounce((query) => {
fetch(`/api/search?q=${query}`);
}, 500);
// 取消 debounce(unmount 時)
handleSearch.cancel();
// 立即執行 + 取消 pending
handleSearch.flush();
React 用時要用 useMemo:
import { useMemo } from 'react';
import debounce from 'lodash/debounce';
function Search() {
const handleSearch = useMemo(
() => debounce((q) => fetch(`/api?q=${q}`), 500),
[],
);
useEffect(() => () => handleSearch.cancel(), [handleSearch]);
return <input onChange={(e) => handleSearch(e.target.value)} />;
}
每次 render 別重建 debounce(否則 timer 重置)。
替代套件(2026 觀察)
| 套件 | 特色 |
|---|---|
lodash | 老牌,沒事用這個 |
remeda | 現代 TS-first,API 鏈式 + 型別安全 |
es-toolkit | 2024 出,號稱比 lodash 快 5x、體積小 |
ramda | FP-style,curry / pipe |
// es-toolkit
import { debounce, cloneDeep, groupBy } from 'es-toolkit';
// remeda(pipe-friendly)
import { pipe, groupBy, map } from 'remeda';
const result = pipe(
users,
groupBy((u) => u.age),
map((group) => group.length),
);
2026 年值得試 es-toolkit(在意 bundle size)或 remeda==(TS heavy 專案)。但 lodash 仍是社群最熟的選擇。