Functional Components Life Cycle and useEffect

Functional Components Life Cycle and the useEffect Hook

This page code

import ClientComponent from '@/components/clientComponent'
 
## View Page
 
This is a regular Nextra page with Markdown content.
 
<ClientComponent />

ClientComponent code

The code of the ClientComponent is shown below:

'use client'
 
import { useState, useEffect } from 'react'
 
const catURL=  "https://api.thecatapi.com/v1/images/search?size=full"
const fetcher = () => fetch(catURL).then((res) => res.json())
 
async function fetchData() {
  // Simulate an API call
  let cat = await fetcher()
  return cat[0]
}
 
function DataFetcher() {
  const [data, setData] = useState(null)
 
  useEffect(() => {
    setData(await fetchData()) //.then(setData)
  }, [])
 
  if (!data) return null
 
  return <img src={data.url} width={data.width} height={data.height} />
}
 
export default function ClientComponent() {
  return (  
    <div>
      <DataFetcher />
    </div>
  )
}

View of the Former Code

This is a regular Nextra page with Markdown content.


Functional Components Life Cycle

There are 3 phases in the React Component LifeCycle:

  1. Mounting Phase
  2. Updating Phase
  3. Un-Mounting Phase

useEffect hook

The useEffect is a Hook in React that allows you to perform side effects in function components. Side effects can include

  • data fetching,
  • subscriptions, or
  • manually changing the DOM.

Basic Syntax

useEffect(() => {
  // Side effect code
  return () => {
    // Clean up code (optional)
  };
}, [dependencies]);
  1. The first argument is a function that contains the side effect code.
  2. The return function is for cleanup (optional).
  3. The second argument is an array of dependencies (optional).

Phases and the useEffect hook

After the component is rendered React will run all useEffect hooks defined in that component.

During the mounting phase, a functional component is being created and added to the DOM. In this phase, you typically initialise state and perform any setup that’s needed when the component is first rendered. The useState hook allows you to add state to your functional components. You can initialise state and retrieve the current value and a function to update it.

In the updating phase, the functional component is re-rendered due to changes in its props or state. By using the useEffect hook without a dependency array, the provided function will run on every render.

In the unmounting phase, the functional component is being removed from the DOM. By returning a cleanup function from the useEffect hook, you can specify cleanup operations to be performed when the component is unmounted.

Key points to remember about useEffect

  • Effects run after every render by default. Specifying a dependency array allows you to control when the effect runs.
  • The cleanup function (returned by the effect) runs before the component unmounts and before the effect runs again on re-renders.
  • If you're using an object or function as a dependency, be careful about recreating it on every render, as this can cause unnecessary effect runs.
  • Avoid updating state in an effect without a dependency array, as this can cause infinite loops.