Try @eslint-react/kit@beta
logoESLint React

Custom Rules Of Context

Validates React Context API usage. Includes checks for 'useContext' and other context-related patterns

Overview

This recipe contains custom rules for validating React Context API usage:

  1. noUseContext: Reports usage of useContext and suggests using use instead (React 19+).

noUseContext

Rule

Copy the following into your project (e.g. .config/noUseContext.ts):

.config/noUseContext.ts
import type { RuleFunction } from "@eslint-react/kit";

/** Disallow 'useContext' in React 19+. Prefer 'use' instead. */
export function noUseContext(): RuleFunction {
  return (context, { is }) => ({
    CallExpression(node) {
      if (is.useContextCall(node)) {
        context.report({
          node: node.callee,
          message: "In React 19, 'use' is preferred over 'useContext' because it is more flexible.",
        });
      }
    },
  });
}

Config

eslint.config.ts
import eslintReactKit from "@eslint-react/kit";
import { noUseContext } from "./.config/noUseContext";

export default [
  // ... other configs
  {
    ...eslintReactKit()
      .use(noUseContext)
      .getConfig(),
    files: ["src/**/*.tsx"],
  },
];

Examples

Invalid

import { useContext } from "react";

function Button() {
  const theme = useContext(ThemeContext);
  //            ^^^^^^^^^^ In React 19, 'use' is preferred over 'useContext' because it is more flexible.
  // ...
}

Valid

import { use } from "react";

function Button() {
  const theme = use(ThemeContext);
  // ...
}

Reports when useContext is used. The use API is more flexible than useContext because it can be called in loops and conditional statements.

Using All Rules

To use all context-related rules together:

eslint.config.ts
import eslintReactKit from "@eslint-react/kit";
import {
  noUseContext,
  // Additional context rules can be added here
} from "./.config";

export default [
  // ... other configs
  {
    ...eslintReactKit()
      .use(noUseContext)
      .getConfig(),
    files: ["src/**/*.tsx"],
  },
];

Further Reading

Resources

  • AST Explorer - A tool for exploring the abstract syntax tree (AST) of JavaScript code, which is essential for writing custom rules.
  • ESLint Developer Guide - Official ESLint documentation for creating custom rules.
  • Using the TypeScript Compiler API - TypeScript compiler API documentation for working with type information in custom rules.

See Also

On this page