DEV Community

Cover image for React useEffect Hook
Collins Mutai
Collins Mutai

Posted on

1

React useEffect Hook

A react hook that runs after component's first render. It has to be called inside a component function like all react hooks.

import {useEffect} from 'react';

useEffect(()=> {
console.log('useeffect running')
},[])
Enter fullscreen mode Exit fullscreen mode

The useEffect is useful when we want to perform an action when the state of our application changes. For example when getting user input. The state change will trigger the useEffect hook to rerun. The state acts as a dependency.

import {useState} from 'react';

const [userInput, setUserInput]= useState('')

useEffect(()=> {
console.log('useeffect running')
}, [userInput])
Enter fullscreen mode Exit fullscreen mode

Finally the useEffect allows us to run cleanup actions. The clean up function runs right after the dependencies change but before the useEffect is triggered by the new dependency.

useEffect(()=> {
console.log('useeffect running')

return ()=> {
console log('cleanup function')
}
})
Enter fullscreen mode Exit fullscreen mode

Together with other react hooks, useEffect hook is a powerful tool to build react applications.

Sentry blog image

How I fixed 20 seconds of lag for every user in just 20 minutes.

Our AI agent was running 10-20 seconds slower than it should, impacting both our own developers and our early adopters. See how I used Sentry Profiling to fix it in record time.

Read more

Top comments (0)

nextjs tutorial video

Youtube Tutorial Series 📺

So you built a Next.js app, but you need a clear view of the entire operation flow to be able to identify performance bottlenecks before you launch. But how do you get started? Get the essentials on tracing for Next.js from @nikolovlazar in this video series 👀

Watch the Youtube series