useEffect is not defined ReferenceError in React [Solved]

avatar

Borislav Hadzhiev

Last updated: May 2, 2022

banner

Photo from Unsplash

useEffect is not defined ReferenceError in React [Solved] #

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

useeffect is not defined

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

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

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

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

The useEffect hook takes a function and a dependencies array as parameters.

Every time one of the dependencies changes, the function is reran.

If you only want to invoke the function when the component mounts, pass an empty dependencies array to the hook.

App.js
useEffect(() => { console.log('Only runs on mount'); }, []); // 👈️ empty dependencies array

If you need to run some logic when the component unmounts, return a function from useEffect.

App.js
useEffect(() => { console.log('Only runs on mount'); return () => { console.log('Only runs on unmount') } }, []); // 👈️ empty dependencies array

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: useEffect is not defined" occurs when we use the useEffect hook in our code but forget to import it. To solve the error, import the hook before using it - import {useEffect} 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.