Course contentsShow
← React
Lesson 639 of 2,39617. Common useEffect MistakesFree lesson

JSON.stringify as a Last Resort

Understand when and why JSON.stringify(obj) in dependencies works, and why it's usually a code smell.

JSON.stringify as a Last Resort

What you'll learn: When and why JSON.stringify(obj) can make object dependencies work in useEffect, and why it's usually a sign of deeper problems.

The Technique

Sometimes developers use JSON.stringify to convert an object into a string for the dependency array:

useEffect(() => {
  // do something with config
}, [JSON.stringify(config)]);

Since strings are primitives, React compares them by value instead of reference. If config has the same contents, the stringified version stays identical, preventing unnecessary effect re-runs.

Why It Works

Objects like { theme: 'dark' } fail reference equality even when identical. But '{"theme":"dark"}' is just a string—same value every time the contents match. The effect only re-runs when the contents actually change.

Why It's a Code Smell

This approach has serious drawbacks:

  • Performance cost: Stringifying large objects on every render is expensive
  • Key order matters: {a:1, b:2} and {b:2, a:1} produce different strings
  • Circular references break it: Nested objects cause runtime errors
  • Hides the real problem: You're working around unstable references instead of fixing them

Better solutions you already know: move objects outside the component, use useMemo, or destructure only the specific properties you need into the dependency array.

When It's Acceptable

Rarely, for small config objects you don't control (like third-party library options), this might be pragmatic. But treat it as a temporary hack, not standard practice.

Key Takeaway: JSON.stringify in dependencies technically prevents unnecessary re-runs, but it's a performance tax that usually signals you should fix the object's stability higher up the component tree instead.