Logo
READLEARNKNOWCONNECT
Back to Lessons

    Page

  • - What Are Side Effects?
  • - What is useEffect?
  • - useEffect Dependency Array
  • - Fetching Data with useEffect
  • - Cleaning Up Effects
  • - Mini Project Step

9. React Hooks: useEffect and Side Effects

Level: BeginnerDuration: 22m

What Are Side Effects?

Side effects are actions that happen outside the normal flow of rendering UI. Examples include fetching data from an API, working with timers or updating the document title.

What is useEffect?

The useEffect hook lets us run side effects in React components. It runs after the component renders.

jsx
import { useEffect } from 'react'

useEffect(() => {
  console.log('Component rendered')
})

This effect runs after every render. But sometimes we only want it to run once or when a value changes, so we use a dependency array.

useEffect Dependency Array

jsx
// Runs only once when the component loads
useEffect(() => {
  console.log('Runs once')
}, [])
jsx
// Runs when count changes
useEffect(() => {
  console.log('Count changed')
}, [count])

Fetching Data with useEffect

A common use of useEffect is fetching data from an API.

jsx
import { useState, useEffect } from 'react'

function Users() {
  const [users, setUsers] = useState([])

  useEffect(() => {
    fetch('https://jsonplaceholder.typicode.com/users')
      .then(response => response.json())
      .then(data => setUsers(data))
  }, [])

  return (
    <ul>
      {users.map(user => <li key={user.id}>{user.name}</li>)}
    </ul>
  )
}

export default Users

Cleaning Up Effects

Some effects need cleanup to avoid memory leaks, like timers or subscriptions. Return a cleanup function from useEffect.

jsx
useEffect(() => {
  const timer = setInterval(() => {
    console.log('Timer running')
  }, 1000)

  return () => clearInterval(timer) // cleanup
}, [])

Mini Project Step

In your project, update `App.jsx` to automatically change the page title based on your feature list count using useEffect.

jsx
// App.jsx
import { useState, useEffect } from 'react'

function App() {
  const [features, setFeatures] = useState(['Reusable components', 'Fast rendering'])

  useEffect(() => {
    document.title = `Project Features: ${features.length}`
  }, [features])

  return (
    <div>
      <h1>Project Features</h1>
      <ul>
        {features.map((feature, index) => (
          <li key={index}>{feature}</li>
        ))}
      </ul>
    </div>
  )
}

export default App