DEV Community

Cover image for React useEffect Hook
Collins Mutai
Collins Mutai

Posted on

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.

Top comments (0)