DEV Community

Cover image for React useEffect And What Is It?
Ahmed Radwan
Ahmed Radwan

Posted on

4

React useEffect And What Is It?

React Side Effect What is it with examples?

You may want to run some code after rendering without running that code in the render() method itself. The useEffect function runs after the JSX component return.

Examples:
All sort of codes will effect your app from outside: API, websockets, local storage and multiple states need to be in sync


When does React run useEffect? and when does NOT?

Runs the first time with the first render and for each other re-render of the component it must check first on the dependency array.


What is the dependency array?

This is an important part of the useEffect function, it's an array containing the dependencies, these dependencies will be the conditions that the useEffect function will only run when they change.


useEffect Example:

// import useEffect 
import { useEffect } from 'react';

 function MyComponent() { 
// We create the count state to include it in the useEffect 
   dependency array
   const [count, setCount] = React.useState(0); 

// Arguments: function and array 
// Count is one of dependencies 
   useEffect(() => {}, [count]); 
// will run useEffect when count has different value than 0

// JSX component return
 return ... }
Enter fullscreen mode Exit fullscreen mode

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Dive into an ocean of knowledge with this thought-provoking post, revered deeply within the supportive DEV Community. Developers of all levels are welcome to join and enhance our collective intelligence.

Saying a simple "thank you" can brighten someone's day. Share your gratitude in the comments below!

On DEV, sharing ideas eases our path and fortifies our community connections. Found this helpful? Sending a quick thanks to the author can be profoundly valued.

Okay