Borislav Hadzhiev
Mon May 02 2022·2 min read
Photo by Steven Roussel
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'
.
// 👇️ 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.
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.
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
.
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: