Skip to main content

Command Palette

Search for a command to run...

useEffect Hook

Published
•2 min read•View as Markdown

What is useEffect?

useEffect is a React hook which is used to handle side effects which occur in a component due to state change. It's basic syntax is useEffect(callback, [...dependencies]).

Dependecy array

By default useEffect runs every time the component re - renders. So we can use it to do something like this:

 useEffect( () => {
        console.log('render')
   })

This will print every time our page render so it provides number of times the page rendered. But what if we want to subscribe to changes occurring in a specific resource ? For that useEffect takes another parameter called dependency array, which takes the resource type you want to subscribe and it will fire the useEffect callback function only when that resource type changes.


const [theme,setTheme] = useState('dark')

console.log('render');

 useEffect( () => {
        console.log('Theme changed')
   },[theme])

return ( 
  <> 
        <button onClick={() => setTheme('dark')}> Dark </button>
        <button onClick={() => setTheme('light')}> Light </button>
</>
)

Here we are setting theme type dark or light based on the button pressed but logging it only when the theme changes using useEffect hook and it will log every time render of component occurs. So , if we click dark theme button then light theme button alternatively then it will log Theme Changed and render in the console , but if we click dark theme button various times , it won't log Theme Changed only the render will log several times it even though the component is re - rendering and that is because the resource data theme is not changing hence it does not fire the useEffect hook.

We can run useEffect only once after the first render and it won't fire again by passing an empty dependency array.

 useEffect( () => {
        const response = api.fetch();
   }, [ ] )

We usually use this for api calls to initialize our states.

Cleanup of useEffect

In useEffect we can pass a cleanup function if we want to clean whatever was done in previous firing of the function


 useEffect( () => {
        console.log('Resource change')

return () => console.log('Return from resource change')
   },[resourceChange])

So now every time the resource changes , after the first time , the return code 'Return from resource change' will be logged before logging 'Resource change' . This is done so that if we attach an event listener then we don't constantly re - add the event listener every time.

G
Ghost3y ago

This is a great tutorial Uday! I'm still trying to wrap my head around useEffect cleanup , as I've heard it shouldn't be always done, just in cases where memory leaks are guaranteed to happen.