Skip to content
← Back to rules

react/use-memo 正确性

功能

验证 useMemo() hook 的使用是否存在常见错误,例如传入异步或生成器回调,或错误使用其参数。

由 React Compiler 提供支持,它每个文件运行一次,并与其他 React Compiler 规则共享。移植自 react-hooks/use-memo

为什么这是不好的?

异步或生成器回调会使 useMemo 记忆化一个 promise 或迭代器,而不是预期的值;错误使用参数则会导致记忆化功能完全无法工作。

示例

此规则的错误代码示例:

jsx
import { useMemo } from "react";
function Component({ a }) {
  const x = useMemo(async () => {
    await a;
  }, [a]);
  return <div>{x}</div>;
}

此规则的正确代码示例:

jsx
import { useMemo } from "react";
function Component({ a }) {
  const x = useMemo(() => a + 1, [a]);
  return <div>{x}</div>;
}

如何使用

To enable this rule using the config file or in the CLI, you can use:

json
{
  "plugins": ["react"],
  "rules": {
    "react/use-memo": "error"
  }
}
ts
import { defineConfig } from "oxlint";

export default defineConfig({
  plugins: ["react"],
  rules: {
    "react/use-memo": "error",
  },
});
bash
oxlint --deny react/use-memo --react-plugin

版本

此规则在 vnext 中添加。

参考