AbsoluteJS

absolute/no-unnecessary-key

Enforce that the key prop is only used on elements rendered as part of an array mapping.

React & JSXProblem
View on GitHub

#Rule Details

Enforces that the React key prop is only used where it is meaningful: on elements rendered as part of an array mapping. A key on a static, one-off element is noise — it implies a list that is not there and can mask real reconciliation bugs.

An element with key is allowed when an ancestor is a .map(...) call (including nested maps) or a return statement (a render helper). A key on an element that is assigned to a variable and then returned, or otherwise sits outside a map/return, is reported.

#Examples

Incorrect
TSX
const Header = () => <div key="main">Hello</div>;

const Build = () => {
	const el = <div key="a" />; // key is not directly in a map or return
	return el;
};
Correct

key inside an array mapping

TSX
const List = () => items.map((item) => <Row key={item.id} {...item} />);
TSX
function renderRow() {
	return <Row key="header" />; // directly returned from a function
}

const Solo = () => <Row />; // no key needed

#Configuration

Enable this rule in your ESLint configuration:

JS
{
	rules: {
		'absolute/no-unnecessary-key': 'error'
	}
}

#When Not To Use It

If you use key deliberately outside of lists to force remounts (resetting component state by changing the key), this rule will flag that valid pattern — disable it on those lines.

#Resources