Skip to content

Instantly share code, notes, and snippets.

@CastonPursuit
Created May 9, 2024 14:01
Show Gist options
  • Save CastonPursuit/7369df62ba65be003914d82959c01577 to your computer and use it in GitHub Desktop.
Save CastonPursuit/7369df62ba65be003914d82959c01577 to your computer and use it in GitHub Desktop.

Understanding useEffect Execution

useEffect is used to perform side effects in functional components. These are operations that can interact with the outside world, such as API requests, timers, DOM manipulations, or subscriptions.

What is a Side Effect?

A side effect in programming occurs when a function or expression modifies some state outside its local environment, or has an observable interaction with the outside world besides returning a value. This could involve:

  • Modifying any external variable or object property.
  • Logging to the console.
  • Writing to a file.
  • Updating the DOM directly.
  • Making an API call.
  • Triggering any external process.
  • Changing any system state that is observable outside the called function.

In the context of React, side effects are operations that need to be controlled to ensure they do not disrupt the rendering flow. This is typically managed using the useEffect hook, which allows you to orchestrate when and how these side effects are executed relative to component rendering cycles.

No Dependency Array

When no dependency array is provided with useEffect, the effect runs after the initial mount and after every subsequent update (re-render). This is because React assumes that the effect might need to run again if anything within the component has changed that could affect the effect.

useEffect(() => {
  // Code here runs after every render (initial mount and every update)
});
Empty Dependency Array (`[]`)

Providing an empty dependency array to useEffect causes the effect to run only once after the initial mount, similar to componentDidMount in class components. This setup indicates to React that the effect does not depend on any props or state values, so it does not need to re-run.

useEffect(() => {
  // Code here runs only once after the initial mount
}, []);
With Dependencies (`[deps]`)

Specifying dependencies in the dependency array of useEffect means the effect will run after the initial mount and then only if one or more of the dependencies have changed since the last effect execution. This allows you to optimize performance by only re-running the effect when necessary.

useEffect(() => {
  // Code here runs after the initial mount and whenever any dependency changes
}, [dep1, dep2]);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment