new·The score now tells you which way it movedA brain's exam only ever grows: its own material writes questions, and so does every question a real caller asked and did not get answered. The score is a percentage over that growing set, so a brain that learned more could post a smaller number — and this week three did. One of them answered two MORE questions than the week before and showed eighteen points less. Printed as a single percentage, that reads as decline to a reader and as punishment to anyone who contributes material.all news →
mozg.beta
Sign in

React · API reference · all subjects

eslint-plugin-react-hooks

160 notes in this subject, read out of this brain and free to use. This is page 1 of 3.

gating ESLint rule

The gating rule validates configuration of gating mode. It is included in the recommended preset of eslint-plugin-react-hooks.

set-state-in-render ESLint rule

The set-state-in-render rule validates against setting state during render. It is included in the recommended preset of eslint-plugin-react-hooks.

incompatible-library ESLint rule

The incompatible-library rule validates against usage of libraries which are incompatible with memoization. It is included in the recommended preset of eslint-plugin-react-hooks.

React Compiler diagnostic violations do not require immediate fixing

When the eslint-plugin-react-hooks reports React Compiler diagnostics, violations do not need to be fixed immediately. Violations can be addressed at your own pace to gradually increase the number of optimized components.

unsupported-syntax ESLint rule

The unsupported-syntax rule validates against syntax that React Compiler does not support. It is included in the recommended preset of eslint-plugin-react-hooks.

eslint-plugin-react-hooks purpose

eslint-plugin-react-hooks provides ESLint rules to enforce the Rules of React. It helps catch violations of React's rules at build time, ensuring components and hooks follow React's rules for correctness and performance. The plugin covers fundamental React patterns like exhaustive-deps and rules-of-hooks, plus issues flagged by React Compiler.

exhaustive-deps ESLint rule

The exhaustive-deps rule validates that dependency arrays for React hooks contain all necessary dependencies. It is included in the recommended preset of eslint-plugin-react-hooks.

use-memo ESLint rule

The use-memo rule validates usage of the useMemo hook without a return value. It is included in the recommended preset of eslint-plugin-react-hooks.

error-boundaries ESLint rule

The error-boundaries rule validates usage of Error Boundaries instead of try/catch for child errors. It is included in the recommended preset of eslint-plugin-react-hooks.

component-hook-factories ESLint rule

The component-hook-factories rule validates higher order functions defining nested components or hooks. It is included in the recommended preset of eslint-plugin-react-hooks.

refs ESLint rule

The refs rule validates correct usage of refs, not reading or writing during render. It is included in the recommended preset of eslint-plugin-react-hooks.

set-state-in-effect ESLint rule

The set-state-in-effect rule validates against calling setState synchronously in an effect. It is included in the recommended preset of eslint-plugin-react-hooks.

preserve-manual-memoization ESLint rule

The preserve-manual-memoization rule validates that existing manual memoization is preserved by the compiler. It is included in the recommended preset of eslint-plugin-react-hooks.

purity ESLint rule

The purity rule validates that components and hooks are pure by checking known-impure functions. It is included in the recommended preset of eslint-plugin-react-hooks.

immutability ESLint rule

The immutability rule validates against mutating props, state, and other immutable values. It is included in the recommended preset of eslint-plugin-react-hooks.

rules-of-hooks ESLint rule

The rules-of-hooks rule validates that components and hooks follow the Rules of Hooks. It is included in the recommended preset of eslint-plugin-react-hooks.

config ESLint rule

The config rule validates the compiler configuration options. It is included in the recommended preset of eslint-plugin-react-hooks.

React Compiler automatic diagnostics and skipping

When React Compiler detects a diagnostic, it means the compiler statically detected a pattern that is not supported or breaks the Rules of React. The compiler automatically skips over those components and hooks while keeping the rest of the app compiled. This ensures optimal coverage of safe optimizations that will not break the app.

globals ESLint rule

The globals rule validates against assignment and mutation of globals during render. It is included in the recommended preset of eslint-plugin-react-hooks.

Common React Compiler configuration mistakes

Common configuration mistakes include: misspelling option names like 'compilationMod' instead of 'compilationMode', passing incorrect value types like boolean instead of string for panicThreshold, and using undocumented options like 'optimizationLevel'.

babel-plugin-react-compiler configuration example

Valid babel-plugin-react-compiler configuration: ```js module.exports = { plugins: [ ['babel-plugin-react-compiler', { compilationMode: 'infer', panicThreshold: 'critical_errors' }] ] }; ```

panicThreshold option valid values

The panicThreshold option for babel-plugin-react-compiler accepts the string values 'none', 'critical_errors', or 'all_errors'. Passing a boolean value like true is invalid.

compilationMode option valid values

The compilationMode option for babel-plugin-react-compiler accepts the values 'all' or 'infer'. The value 'everything' is invalid.

eslint-plugin-react-hooks config rule validates React Compiler configuration

The config rule validates that babel-plugin-react-compiler configuration uses correct option names and value types. It prevents silent failures from typos or incorrect settings by checking against the React Compiler's documented configuration options.

Valid: Custom hook at module level

Custom hooks should be defined at the module level with parameters. Example: function useData(endpoint) { } This ensures the hook can be called consistently and maintain proper state.

Valid: Component defined at module level

Components should be defined at the module level with props. Example: function Component({ defaultValue }) { } This allows React to properly manage component identity and state.

Invalid: Component defined inside component

Defining a component inside another component function is invalid. Example: function Parent() { function Child() { } return <Child />; } This creates a new component on every render.

Invalid: Hook factory function

A factory function that returns a custom hook is invalid. Example: function createCustomHook(endpoint) { return function useData() { }; } Hooks should be defined at the module level, not created dynamically.

Why nested component/hook definitions cause problems

Defining components or hooks inside other functions creates new instances on every call. React treats each as a completely different component, destroying and recreating the entire component tree, losing all state, and causing performance problems.

component-hook-factories ESLint rule purpose

The component-hook-factories ESLint rule validates against higher order functions defining nested components or hooks. Components and hooks should be defined at the module level, not inside other functions.

Invalid: Factory function creating components

A factory function that returns a new component function is invalid. Example: function createComponent(defaultValue) { return function Component() { }; } This pattern creates new component instances on each factory call.

Dynamic component behavior: correct pattern with props

Instead of factory patterns, pass values as props to a single module-level component. Example: function Button({color, children}) { return <button style={{backgroundColor: color}}>{children}</button>; } Then use it with different props: <Button color="red">Red</Button> and <Button color="blue">Blue</Button>

Dynamic component behavior: wrong factory pattern

Creating components via factory pattern is wrong. Example: function makeButton(color) { return function Button({children}) { return <button style={{backgroundColor: color}}>{children}</button>; }; } const RedButton = makeButton('red');

error-boundaries rule: invalid pattern with try/catch around use hook

Do not wrap the use hook in a try/catch block. When use encounters a pending promise, it suspends the component rather than throwing an error. The catch block would never run, making the try/catch ineffective and misleading.

error-boundaries rule: use hook suspends instead of throwing

The use hook does not throw errors in the traditional sense; it suspends component execution. When use encounters a pending promise, it suspends the component and lets React show a fallback. Try/catch cannot handle suspension. Only Suspense and Error Boundaries can handle these cases.

error-boundaries rule: correct pattern for use hook with Suspense and ErrorBoundary

To handle the use hook correctly, wrap the component in both an ErrorBoundary and a Suspense component. The Suspense handles the loading state when use suspends on a pending promise, and the ErrorBoundary handles any actual errors that occur.

error-boundaries rule: correct pattern with ErrorBoundary component

To handle rendering errors from child components, wrap them in an ErrorBoundary component rather than using try/catch. An ErrorBoundary is a class component that implements componentDidCatch() or getDerivedStateFromError() lifecycle methods and will catch any errors thrown by its child components during rendering.

error-boundaries rule: invalid pattern with try/catch around JSX

Do not wrap a component's JSX return in a try/catch block. For example, wrapping <ChildComponent /> in try/catch will not catch errors thrown during its rendering, because try/catch only handles thrown exceptions in the try block itself, not errors from child component render methods or hooks.

error-boundaries rule: try/catch cannot catch render errors

The error-boundaries ESLint rule validates that Error Boundaries are used instead of try/catch for errors in child components. Try/catch blocks cannot catch errors that happen during React's rendering process. Errors thrown in rendering methods or hooks bubble up through the component tree. Only Error Boundaries can catch these errors.

gating configuration example with feature flags

Valid gating configuration example: module.exports = { plugins: [['babel-plugin-react-compiler', { gating: { importSpecifierName: 'isCompilerEnabled', source: 'featureFlags' } }]] }; where featureFlags.js exports function isCompilerEnabled() { ... }

omitting gating field compiles all components

If the gating field is completely omitted from babel-plugin-react-compiler configuration, React Compiler will process all components without gating.

gating must be an object, not a string

The gating configuration must be an object with importSpecifierName and source fields. Passing gating as a string value directly is invalid.

gating configuration requires importSpecifierName and source fields

When using gating mode in babel-plugin-react-compiler, the gating object must include two required fields: importSpecifierName (the exported function name that gates compilation) and source (the module name where the gating function is exported). Missing either field is invalid configuration.

gating rule validates compiler gating configuration

The eslint-plugin-react-hooks gating rule validates configuration of gating mode for React Compiler. Gating mode allows gradual adoption of React Compiler by marking specific components for optimization. This rule ensures gating configuration is valid so the compiler knows which components to process.

Running effect only once with dependency

When you want an effect to run only once on mount but the linter complains about missing dependencies, the recommended approach is to include the dependency: useEffect(() => { sendAnalytics(userId); }, [userId]);

exhaustive-deps additionalEffectHooks configuration

The exhaustive-deps rule can be configured with additionalEffectHooks in ESLint shared settings (available in eslint-plugin-react-hooks 6.1.1 and later). This option accepts a regex pattern matching custom hooks that should be checked for exhaustive dependencies. Configuration example: { "settings": { "react-hooks": { "additionalEffectHooks": "(useMyEffect|useCustomEffect)" } } }

Running effect only once with useRef guard

As an alternative to including dependencies, you can use a ref guard inside the effect to ensure it runs only once: const sent = useRef(false); useEffect(() => { if (sent.current) { return; } sent.current = true; sendAnalytics(userId); }, [userId]);

exhaustive-deps rule purpose

The exhaustive-deps ESLint rule validates that dependency arrays for React hooks contain all necessary dependencies. It checks hooks like useEffect, useMemo, and useCallback to ensure that when a value is referenced inside the hook, it is included in the dependency array. If a dependency is missing, React won't re-run the effect or recalculate the value when that dependency changes, causing stale closures where the hook uses outdated values.

Function dependency solution: move logic into effect

To avoid infinite loops from function dependencies, move the function logic directly into the effect instead of calling a separate function: useEffect(() => { console.log(items); }, [items]);

Function dependency solution: call from event handler

To avoid infinite loops from function dependencies, call the function directly from an event handler instead of in an effect: const logItems = () => { console.log(items); }; return <button onClick={logItems}>Log</button>;

Function dependency infinite loop problem

When a function is created inside the component and used as an effect dependency, it causes an infinite loop because a new function is created on every render. For example: const logItems = () => { console.log(items); }; useEffect(() => { logItems(); }, [logItems]); // Infinite loop!

exhaustive-deps valid example: fetchUser with dependency

The following code passes exhaustive-deps because userId is included in the dependency array: useEffect(() => { fetchUser(userId); }, [userId]);

exhaustive-deps valid example: all dependencies included

The following code passes exhaustive-deps because all referenced values are in the dependency array: useEffect(() => { console.log(count); }, [count]);

Function dependency solution: useCallback

To keep a function reference stable and avoid infinite loops with effect dependencies, wrap the function with useCallback: const logItems = useCallback(() => { console.log(items); }, [items]); useEffect(() => { logItems(); }, [logItems]);

exhaustive-deps invalid example: incomplete dependencies in useMemo

The following code violates the exhaustive-deps rule because sortOrder is referenced inside useMemo but not included in the dependency array: useMemo(() => { return items.sort(sortOrder); }, [items]); // Missing 'sortOrder'

exhaustive-deps invalid example: missing userId prop

The following code violates the exhaustive-deps rule because userId is referenced inside the effect but not included in the dependency array: useEffect(() => { fetchUser(userId); }, []); // Missing 'userId'

exhaustive-deps invalid example: missing count variable

The following code violates the exhaustive-deps rule because the count variable is referenced inside the effect but not included in the dependency array: useEffect(() => { console.log(count); }, []); // Missing 'count'

exhaustive-deps additionalHooks rule-level option

For backward compatibility, exhaustive-deps also accepts a rule-level additionalHooks option as a regex for hooks that should be checked for exhaustive dependencies. Configuration example: { "rules": { "react-hooks/exhaustive-deps": ["warn", { "additionalHooks": "(useMyCustomHook|useAnotherHook)" }] } } Note: If this rule-level option is specified, it takes precedence over the shared settings configuration.

immutability rule validates against mutating props and state

The immutability ESLint rule validates that you do not mutate props, state, and other immutable values in React components. Props and state are immutable snapshots and should never be mutated directly.

Never mutate array state with push()

Using Array.push() to add items to state will mutate the array in place. Since the array reference remains the same, React will not trigger a re-render. Instead, create a new array using spread syntax: setItems([...items, newValue]).

Give your agent this brain