Skip to content
项目

nickjvandyke/eslint-plugin-react-you-might-not-need-an-effect

在 GitHub 查看

关于

🙅‍♂️ 检测不必要的 React effect,让代码更简单、更快、更安全。

网站与应用开发

这些数字如何统计

实测星标增长

24小时
+3
7天
+4
15天
+10
1个月
+15

各周期内的星标净变化,周期相互重叠,并非每日新增。缺失的测量保持空白。星标代表关注度,不代表软件质量。

README.md

原文

ESLint – React – You Might Not Need An Effect

NPM version NPM Downloads

ESLint (and Oxlint) plugin to catch unnecessary useEffects to make your React code easier to follow, faster to run, and less error-prone. Highly recommended for new React developers as you learn React's mental model. Even experienced developers will likely learn something new!

function Form() {
  const [firstName, setFirstName] = useState("Nick");
  const [lastName, setLastName] = useState("van Dyke");

  const [fullName, setFullName] = useState("");
  useEffect(() => {
    // ❌ Avoid storing derived state. Instead, compute `fullName` during render.
    // 📖 react.dev/learn/you-might-not-need-an-effect#updating-state-based-on-props-or-state
    setFullName(firstName + " " + lastName);
  }, [firstName, lastName]);
}
  • Actionable guidance: Reports each anti-pattern with a specific suggested alternative and a docs link.
  • Deep analysis: Analyzes state, props, contexts, refs, and their upstream sources.
  • Dependency-conscious: Considers when an effect runs to determine if its logic is actually redundant.
  • Edge-case obsessed: Focuses on unusual syntax and heuristics to keep the signal-to-noise ratio high.
  • Library-aware: Recognizes popular third-party useEffect wrappers.

Used by Docusaurus (Meta), Primer (GitHub), Sentry, Langfuse, Clerk and 700+ GitHub public repositories.

📦 Installation

NPM

npm install --save-dev eslint-plugin-react-you-might-not-need-an-effect

Yarn

yarn add -D eslint-plugin-react-you-might-not-need-an-effect

⚙️ Configuration

Flat Config

// eslint.config.js
import reactYouMightNotNeedAnEffect from "eslint-plugin-react-you-might-not-need-an-effect";

export default [
  // Enable every rule as a warning
  reactYouMightNotNeedAnEffect.configs.recommended,
  // Or enable every rule as an error
  reactYouMightNotNeedAnEffect.configs.strict,
  // Or enable only specific rules
  {
    plugins: {
      reactYouMightNotNeedAnEffect,
    },
    rules: {
      "reactYouMightNotNeedAnEffect/no-derived-state": "warn",
    },
    languageOptions: {
      parserOptions: {
        ecmaFeatures: {
          jsx: true,
        },
      },
    },
  },
];

Legacy Config

// .eslintrc
{
  "extends": [
    // Enable every rule as a warning
    "plugin:react-you-might-not-need-an-effect/legacy-recommended",
    // Or enable every rule as an error
    "plugin:react-you-might-not-need-an-effect/legacy-strict",
  ],
  // Or enable only specific rules
  "plugins": ["react-you-might-not-need-an-effect"],
  "rules": {
    "react-you-might-not-need-an-effect/no-derived-state": "warn",
  },
  "parserOptions": {
    "ecmaFeatures": {
      "jsx": true,
    },
  },
}

Oxlint

Use this plugin with Oxlint thanks to their JS plugin support!

// oxlint.config.ts
import reactYouMightNotNeedAnEffect from "eslint-plugin-react-you-might-not-need-an-effect";
import { defineConfig } from "oxlint";

export default defineConfig({
  jsPlugins: ["eslint-plugin-react-you-might-not-need-an-effect"],
  rules: {
    // Enable every rule as a warning
    ...reactYouMightNotNeedAnEffect.configs.recommended.rules,
    // Or enable every rule as an error
    ...reactYouMightNotNeedAnEffect.configs.strict.rules,
    // Or enable only specific rules
    "react-you-might-not-need-an-effect/no-derived-state": "warn",
  },
});

Suggested

Enforce these other rules in your codebase for more accurate analysis:

🔎 Rules

See the rule tests for extensive (in)valid examples and the property tests for the generated syntax combinations each rule is tested against.

React's eslint-plugin-react-hooks/set-state-in-effect rule flags synchronous setState calls inside effects, helping prevent unnecessary re-renders. However, unnecessary effects go far beyond this.

no-derived-state

Disallow storing derived state in an effect:

function Form() {
  const [firstName, setFirstName] = useState("Nick");
  const [lastName, setLastName] = useState("van Dyke");

  const [fullName, setFullName] = useState("");
  useEffect(() => {
    // ❌ Avoid storing derived state. Instead, compute `fullName` during render.
    // 📖 react.dev/learn/you-might-not-need-an-effect#updating-state-based-on-props-or-state
    setFullName(firstName + " " + lastName);
  }, [firstName, lastName]);
}

no-chain-state-updates

Disallow chaining state updates in an effect:

function Game() {
  const [round, setRound] = useState(1);
  const [isGameOver, setIsGameOver] = useState(false);

  useEffect(() => {
    if (round > 10) {
      // ❌ Avoid chaining state changes. The effect sets `isGameOver` when the state `round` changes. Instead, compute `isGameOver` during render, or set it in the same event handler that changes `round`.
      // 📖 react.dev/learn/you-might-not-need-an-effect#chains-of-computations
      setIsGameOver(true);
    }
  }, [round]);
}

no-event-handler

Disallow using state and an effect as an event handler:

function Form() {
  const [dataToSubmit, setDataToSubmit] = useState();

  useEffect(() => {
    if (dataToSubmit) {
      // ❌ Avoid using state and effects as an event handler. Instead, move this code into the event handler that changes `dataToSubmit`.
      // 📖 react.dev/learn/you-might-not-need-an-effect#sharing-logic-between-event-handlers
      submitData(dataToSubmit);
    }
  }, [dataToSubmit]);
}

Disallow using props and an effect as an event handler:

function ProductPage({ product, addToCart }) {
  useEffect(() => {
    if (product.isInCart) {
      // ❌ Avoid using props and effects as an event handler. Instead, move this code into the parent's event handler that changes `product`.
      // 📖 react.dev/learn/you-might-not-need-an-effect#sharing-logic-between-event-handlers
      showNotification(`Added ${product.name} to the shopping cart!`);
    }
  }, [product]);
}

no-adjust-state-on-prop-change

Disallow adjusting state in an effect when an external value changes. External values are props, useContext values, and hook return values.

function List({ items }) {
  const [isReverse, setIsReverse] = useState(false);
  const [selection, setSelection] = useState(null);

  useEffect(() => {
    // ❌ Avoid adjusting state in response to `items`. Instead, update `selection` during render, guarded by a comparison with a state variable that stores the previous value; an unguarded setter re-renders forever. Or refactor the state so it needs no adjustment.
    // 📖 react.dev/learn/you-might-not-need-an-effect#adjusting-some-state-when-a-prop-changes
    setSelection(null);
  }, [items]);
}

Hook return values behave the same as props, because the hook owns the value:

function Items() {
  const { data } = useQuery("/items");
  const [selection, setSelection] = useState(null);

  useEffect(() => {
    // ❌ Avoid adjusting state in response to `data`. Instead, update `selection` during render, guarded by a comparison with a state variable that stores the previous value; an unguarded setter re-renders forever. Or refactor the state so it needs no adjustment.
    // 📖 react.dev/learn/you-might-not-need-an-effect#adjusting-some-state-when-a-prop-changes
    setSelection(null);
  }, [data]);
}

no-reset-all-state-on-prop-change

Disallow resetting all state in an effect when a prop changes:

function List({ items }) {
  const [selection, setSelection] = useState(null);

  useEffect(() => {
    // ❌ Avoid resetting all state when the prop `items` changes. Instead, add `key={items}` where the parent renders `List`.
    // 📖 react.dev/learn/you-might-not-need-an-effect#resetting-all-state-when-a-prop-changes
    setSelection(null);
  }, [items]);
}

no-pass-live-state-to-parent

Disallow passing live state to parents in an effect from a component:

function Child({ onTextChanged }) {
  const [text, setText] = useState();

  useEffect(() => {
    // ❌ Avoid passing live state to parents in an effect. Instead, lift `text` to the parent and pass it down to `Child` as a prop.
    // 📖 react.dev/learn/you-might-not-need-an-effect#notifying-parent-components-about-state-changes
    onTextChanged(text);
  }, [onTextChanged, text]);
}

Disallow passing live state to parents in an effect from a custom hook:

const useCustomHook = ({ onTextChanged }) => {
  const [text, setText] = useState();

  useEffect(() => {
    // ❌ Avoid passing live state to parents in an effect. Instead, return `text` from `useCustomHook`.
    // 📖 react.dev/learn/you-might-not-need-an-effect#notifying-parent-components-about-state-changes
    onTextChanged(text);
  }, [onTextChanged, text]);
};

no-pass-data-to-parent

Disallow passing data to parents in an effect from a component:

function Child({ onDataFetched }) {
  const { data } = useQuery("/data");

  useEffect(() => {
    // ❌ Avoid passing data to parents in an effect. Instead, load or compute `data` in the parent and pass it down to `Child` as a prop.
    // 📖 react.dev/learn/you-might-not-need-an-effect#passing-data-to-the-parent
    onDataFetched(data);
  }, [data, onDataFetched]);
}

Disallow passing data to parents in an effect from a custom hook:

const useCustomHook = ({ onFetched }) => {
  const { data } = useQuery("/data");

  useEffect(() => {
    // ❌ Avoid passing data to parents in an effect. Instead, return `data` from `useCustomHook`.
    // 📖 react.dev/learn/you-might-not-need-an-effect#passing-data-to-the-parent
    onFetched(data);
  }, [onFetched, data]);
};

no-external-store-subscription

Disallow subscribing to an external store in an effect:

function useOnlineStatus() {
  const [isOnline, setIsOnline] = useState(true);

  useEffect(() => {
    function updateState() {
      setIsOnline(navigator.onLine);
    }

    updateState();
    window.addEventListener("online", updateState);
    window.addEventListener("offline", updateState);
    return () => {
      // ❌ Avoid using an effect to subscribe to an external store. Instead, use `useSyncExternalStore` to manage `isOnline`.
      // 📖 react.dev/learn/you-might-not-need-an-effect#subscribing-to-an-external-store
      window.removeEventListener("online", updateState);
      window.removeEventListener("offline", updateState);
    };
  }, []);
}

no-initialize-state

Disallow initializing state in an effect:

function Greeting() {
  const [greeting, setGreeting] = useState();

  useEffect(() => {
    // ❌ Avoid initializing state in an effect. Instead, initialize `greeting` with `useState("Hello World")` and remove this setter call. For SSR hydration, prefer `useSyncExternalStore`.
    // 📖 tkdodo.eu/blog/avoiding-hydration-mismatches-with-use-sync-external-store
    setGreeting("Hello World");
  }, []);
}

💬 Feedback

The ways to (mis)use an effect in real-world code are practically endless! This plugin is not exhaustive, but tries to be. If you encounter unexpected behavior or see opportunities for improvement, please open an issue or pull request. Your feedback helps improve the plugin for everyone!

📖 Learn More

Deep-dives from the official React documentation:

探索相关项目

加载中…