I encountered the following error while working on a React project using TypeScript:
328:10 Error: 'displayAmount' is assigned a value but never used. @typescript-eslint/no-unused-vars
The error happened because I declared a state variable with useState
, but I never used it in my component.
TypeScript, with @typescript-eslint/no-unused-vars
, enforces that all declared variables should be used to maintain clean and efficient code.
To fix this issue, I considered the following approaches:
If displayAmount
is necessary, ensure it is used somewhere in the component:
const [displayAmount, setDisplayAmount] = useState(amount);
return <div>Amount: {displayAmount}</div>;
This way, TypeScript recognizes the variable as being used, and the error disappears.
If displayAmount
is not needed, I removed it while keeping the state updater function:
const [, setDisplayAmount] = useState(amount);
By using a comma ([,]
), I ignored the first value (displayAmount
), preventing ESLint from flagging it as unused.
If, for some reason, I wanted to keep the variable but avoid the error, I could temporarily disable the rule:
// eslint-disable-next-line @typescript-eslint/no-unused-vars
const [displayAmount, setDisplayAmount] = useState(amount);
However, I don’t recommend this approach unless absolutely necessary,
as it bypasses TypeScript’s helpful checks.
TypeScript enforces clean code practices by warning developers about variables that are declared but not used.
This helps prevent unnecessary memory usage and keeps code readable.
displayAmount
later?If displayAmount
will be used in future logic but isn’t needed yet,
a simple workaround is a temporary console log:
console.log(displayAmount); // Prevents unused variable warning
This keeps the variable in the code while avoiding the ESLint warning.
Yes, unless you plan to use them soon. Keeping unused variables can make the codebase messy and misleading for future maintenance.
If you only need to update state but don’t need the value itself, you can ignore the first element of the useState
array:
const [, setDisplayAmount] = useState(amount);
This ensures setDisplayAmount
remains available while avoiding the warning.
Yes, you can modify your ESLint configuration to allow unused variables in some cases.
However, this is not recommended as it might hide potential coding issues.
If needed, you can add this rule to .eslintrc.json
:
{
"rules": {
"@typescript-eslint/no-unused-vars": ["warn", { "varsIgnorePattern": "^_" }]
}
}
This allows variables prefixed with _
(e.g., _displayAmount
) to be ignored by ESLint.
This guide ensures your React project remains clean while resolving the @typescript-eslint/no-unused-vars
error effectively.