jsx-eslint / eslint-plugin-react

React-specific linting rules for ESLint
MIT License
9.01k stars 2.77k forks source link

Rule Proposal: no-duplicate-use-context #3850

Closed dislido closed 3 weeks ago

dislido commented 3 weeks ago

Within the same component, each context can only be used once at most

const MyContext = React.createContext({ a: 1, b: 2 })

Examples of incorrect code for this rule:

const Component = () => {
  const { a } = useContext(MyContext);
  const { b } = useContext(MyContext);
  return <></>;
}

Examples of correct code for this rule:

const Component = () => {
  const { a, b } = useContext(MyContext);
  return <></>;
}

autofix

Automatically fixable, possibly like eslint-plugin-import/no-duplicates?

ljharb commented 3 weeks ago

What happens in practice when you have two usages?

dislido commented 3 weeks ago

Some components are very large, and useContext is written on the line before using it.

interface CompProps {
  a: string;
}
const Component: React.FC<CompProps> = ({ a }) => {
  // Many lines of code

  const { a: _a } = useContext(MyContext);
  const myAGt1 = _a > 1

  // Many lines of code

  const { a: myA } = useContext(MyContext);
  const myAEq0 = myA === 0;
}

This is indeed a rare situation, usually occurring in the following scenarios:

This will not cause errors, but it adds unnecessary duplicate code

ljharb commented 3 weeks ago

ok, that was my question - there's nothing wrong with it, it's just about organization. It seems like perhaps "many lines of code" is the root problem here, since without an overly long component, nobody would write that?

dislido commented 3 weeks ago

Long components increase the chance of causing this problem. Thinking of it once more I realized that it's not suitable to add this rule to prevent this rare situation