DEV Community

vishwa v
vishwa v

Posted on

react(useEffect)

What does render mean in React?
Render = React drawing your component’s UI on the screen.

Every time React needs to show something new (like updated text, a new list item, or a changed button state), it re-runs your component function and updates the DOM (the browser’s page structure).

When does a render happen?
Initial render → when the component first appears on the page.
Example: opening your app → React draws .

Re-render → whenever state or props change.
Example: typing in the input → text state changes → React redraws the input with the new value.

Why useEffect
useEffect is not about re-rendering — it’s about running side effects after React finishes rendering.

State (useState) → controls your component’s data and triggers re-renders.

Effect (useEffect) → lets you run extra code after the render happens.

Think of it like this:

useState = “React, redraw my component with new data.”

useEffect = “React, after you finish drawing, also do this extra work.”

diff blw useEffect and useState
Rendering with useState:
Whenever you call setState (like setText), React must re-run your component function to update the UI.

Even if the change is small (like typing one letter), React redraws the component.

For a big component with lots of code, yes, React has to go through all of it again — but React is optimized to only update the parts of the DOM that actually changed. So it’s not as “heavy” as it sounds.

Where useEffect fits:
useEffect does not reduce rendering time.

Instead, it’s a place to put side effects (things outside the normal UI update, like fetching data, logging, timers, subscriptions).

The key difference:

useState → triggers re-render when data changes.

useEffect → runs extra code after React finishes rendering.

Cases
No dependency array

jsx
useEffect(() => {
  console.log("Runs after every render");
});
Enter fullscreen mode Exit fullscreen mode

Runs after every render, no matter what changed.

Empty dependency array []

jsx
useEffect(() => {
  console.log("Runs only once (on mount)");
}, []);
Enter fullscreen mode Exit fullscreen mode

Runs only once when the component first loads (like componentDidMount).

With specific dependencies

jsx
useEffect(() => {
  console.log("Text changed:", text);
}, [text]);

Enter fullscreen mode Exit fullscreen mode

Runs only when text changes.
If you type in the input, it logs. If something else re-renders but text didn’t change, it won’t run.

Top comments (0)