Unexpected use of undefined
1import { createContext, useContext, useState } from 'react';
2
3const ThemeContext = createContext(undefined); 4
5function ThemeProvider({ children }) {
6 const [theme, setTheme] = useState("light");
Unexpected use of undefined
9
10function useTheme() {
11 const context = useContext(ThemeContext);
12 if (context === undefined) {13 throw new Error('useTheme must be used within a ThemeProvider');
14 }
15 return context;
Description
The undefined
variable in JavaScript is actually a property of the global object. As such, in ECMAScript 3 it was possible to overwrite the value of undefined
. While ECMAScript 5 disallows overwriting undefined
, it's still possible to shadow undefined, such as:
function doSomething(data) {
var undefined = "hi";
// doesn't do what you think it does
if (data === undefined) {
// ...
}
}
Because undefined
can be overwritten or shadowed, reading undefined
can give an unexpected value. (This is not the case for null
, which is a keyword that always produces the same value.) To guard against this, you can avoid all uses of undefined
.
This ensures that undefined will always hold its original, expected value.
Bad Practice
var foo = undefined;
var undefined = "foo";
if (foo === undefined) {
// ...
}
function foo(undefined) {
// ...
}
Recommended
var foo = void 0;
var Undefined = "foo";
if (typeof foo === "undefined") {
// ...
}
global.undefined = "foo";