useState is not defined ReferenceError in React [Solved]

avatar

Borislav Hadzhiev

Last updated: May 2, 2022

banner

Photo from Unsplash

useState is not defined ReferenceError in React [Solved] #

The "Uncaught ReferenceError: useState is not defined" occurs when we use the useState hook in our code but forget to import it. To solve the error, import the hook before using it - import {useState} from 'react'.

usestate is not defined

App.js
// 👇️ import useState hook import {useState} from 'react'; const App = () => { const [count, setCount] = useState(0); const handleClick = event => { setCount(current => current + 1); }; return ( <div> <h2>Count: {count}</h2> <button onClick={handleClick}>Increment</button> </div> ); }; export default App;

The "'useState' is not defined no-undef" error occurs when we use the useState hook in our code without importing it first.

The useState hook can be imported as a named import from the react package.

App.js
import {useState} from 'react';

The hook returns an array where the first element is the state variable and the second - a setState function that can be used to update the state.

The useState hook can be passed an initial state value as a parameter.

App.js
const [count, setCount] = useState(0);

The example above sets an initial value of 0 for the count state variable.

You can use the setCount function to update the state.

App.js
const [count, setCount] = useState(0); setCount(100);

When the next state is computed using the previous state, you can pass a function to setState.

App.js
const [count, setCount] = useState(0); setCount(current => current + 1);

We passed a function to setState, because the function is guaranteed to be invoked with the current (most up to date) state.

Otherwise, we might get some weird race condition if the state variable we have access to does not represent the most up to date value.

Note that there are some rules when using React hooks.

Like the documentation states:

  • Only call hooks from React function components or from custom hooks.
  • Only call hooks at the top level
  • Don't call hooks inside loops, conditions or nested functions
  • Always use hooks at the top level of your React function, before any early returns

Conclusion #

The "Uncaught ReferenceError: useState is not defined" occurs when we use the useState hook in our code but forget to import it. To solve the error, import the hook before using it - import {useState} from 'react'.

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.