useEffect()
The useEffect()
hook takes in a function and an array. The function will be executed after the current render process finishes and only if the elements inside the array has changed from the previous render.
This hook can be used to run side effects (call to an external API, update another state, etc.) or attach event listeners.
Syntax
The useEffect()
hook accepts a function and an array of dependencies as its first and second parameter respectively. This hook doesn’t return any value.
useEffect(
() => {
// Runs side effect here
},
[] // Array of dependencies
);
If the array of dependencies is empty, the effect will only run once when the component mounts.
The function passed as the first parameter may also return a “cleanup function” that is executed before the next scheduled effect runs. This chance can be used to remove event listeners or abort an API call.
useEffect(() => {// Runs side effect herereturn () => {// Do clean up here};},[] // Array of dependencies);
Example
In the following example, the useEffect()
hook attaches a 'scroll'
listener to the window
object and removes it with a cleanup function:
import React, { useEffect } from 'react';function PageWrapper() {useEffect(() => {function scrollHandler() {console.log('Current scroll position is', window.scrollTop);}window.addEventListener('scroll', scrollHandler);return () => window.removeEventListener('scroll', scrollHandler);}, []); // Runs only once when component mountsreturn <div>Page content...</div>;}
Contribute to Docs
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve Docs.
Learn React on Codecademy
- Career path
Front-End Engineer
Front-end engineers work closely with designers to make websites beautiful, functional, and fast.Includes 34 CoursesWith Professional CertificationBeginner Friendly115 hours - Free course
Learn React
In this React course, you’ll build powerful interactive applications with one of the most popular JavaScript libraries.Intermediate13 hours