eslint-plugin-react icon indicating copy to clipboard operation
eslint-plugin-react copied to clipboard

Suggestion: `no-redundant-key`

Open SimonSchick opened this issue 11 months ago • 4 comments

I noticed that after refactorings we sometimes forgot to remove the key on the root fragment of a new component, this seems to be entirely redundant and just add overhead.

example:

const Component: FC = () => {
          // v key is redundant here
   return <p key={1}>test</test>;
}

This would be effectively the counter-rule to `https://github.com/jsx-eslint/eslint-plugin-react/blob/master/docs/rules/jsx-key

I think a good heuristic would be to match any fragment that is not contained within a callback eg. Array.map.

SimonSchick avatar Jan 16 '25 03:01 SimonSchick

key does serve a purpose, even outside a list - in other words, it's not redundant. See https://kentcdodds.com/blog/understanding-reacts-key-prop

What this means is that I'm not sure there's any way to statically identify a key prop that should be removed, since potentially all of them could be meaningful.

ljharb avatar Jan 16 '25 05:01 ljharb

Related to https://github.com/jsx-eslint/eslint-plugin-react/issues/3148

jroru avatar Apr 29 '25 23:04 jroru

key allows to force a redraw if its value changes. That's not the case with consts

Using const keys / reusing keys outside of arrays could cause memory leaks.

I've come across situations where something like:

const ChildA = () => <React.Fragment key="my-component">...</React.Fragment>:
const ChildB = () => <React.Fragment key="my-component">...</React.Fragment>:

const Parent = (toggle: boolean) => toggle ? <ChildA /> : <ChildB />

results in detached DOM objects and memory leaks

So warning about that could be a good thing!

KuSh avatar Nov 13 '25 23:11 KuSh

I don't think it's possible in a generic sense to warn about that kind of pattern statically.

ljharb avatar Nov 15 '25 05:11 ljharb