nextjs useEffect vs useState

nextjs

In a Next.js app, useEffect and useState are both React hooks that allow you to add functionality to your components.

useState is a hook that allows you to add state to functional components. State is a way to store and manage data in a component, and it can be changed over time. Here’s an example of how to use useState:

import React, { useState } from 'react'

function Example() {
  // Declare a new state variable, which we'll call "count"
  const [count, setCount] = useState(0)

  return (
    <div>
      <p>You clicked {count} times</p>
      <button onClick={() => setCount(count + 1)}>
        Click me
      </button>
    </div>
  )
}

In this example, we use useState to declare a new state variable called count, which is initially set to 0. We also get a function called setCount, which allows us to update the value of count.

We use the count variable to display the number of times the button has been clicked, and we use the setCount function to update the value of count when the button is clicked.

useEffect is a hook that allows you to perform side effects in functional components. A side effect is an operation that has an effect on something outside of the component, such as making a network request or updating the DOM. Here’s an example of how to use useEffect:

import React, { useState, useEffect } from 'react'

function Example() {
  const [data, setData] = useState(null)

  useEffect(() => {
    fetch('https://api.example.com/data')
      .then(response => response.json())
      .then(data => setData(data))
  }, [])

  return (
    <div>
      {data ? (
        <p>{data.message}</p>
      ) : (
        <p>Loading...</p>
      )}
    </div>
  )
}

In this example, we use useEffect to perform a side effect when the component is mounted. We use the fetch function to make a network request to an API and retrieve some data, and then we use the setData function to update the value of the data state variable with the data we received.

The empty array at the end of the useEffect function is called the dependencies array. It tells React to only execute the side effect when the component is mounted (and not on every update). If we wanted the side effect to run on every update, we could pass an array of variables that we want to watch for changes.

In summary, useState is used to add state to a functional component, while useEffect is used to perform side effects in a functional component. Both useState and useEffect are important tools in the React developer’s toolbox, and they can be used together to build powerful and dynamic user interfaces.