{"id":67,"date":"2026-07-04T10:10:26","date_gmt":"2026-07-04T10:10:26","guid":{"rendered":"https:\/\/www.kindsonthegenius.com\/react\/05-react-useeffect\/"},"modified":"2026-07-04T10:14:11","modified_gmt":"2026-07-04T10:14:11","slug":"05-react-useeffect","status":"publish","type":"post","link":"https:\/\/www.kindsonthegenius.com\/react\/05-react-useeffect\/","title":{"rendered":"React useEffect \u2014 Side Effects and Data Fetching (React 19+)"},"content":{"rendered":"<p><!-- ktg-updated-banner --><\/p>\n<div class=\"ktg-updated-banner\" style=\"margin:0 0 1.25em;padding:0.75em 1em;background:#fefce8;border-left:4px solid #ca8a04;border-radius:4px;\">\n<p><strong>Updated July 4, 2026.<\/strong> Refreshed for React 19 and current SEO best practices.<\/p>\n<\/div>\n<p><!-- ktg-series-toc --><\/p>\n<nav class=\"ktg-series-toc\" aria-label=\"React tutorial table of contents\" style=\"margin:1.5em 0;padding:1em 1.25em;background:#f8fafc;border:1px solid #e2e8f0;border-radius:8px;\">\n<h2>Table of Contents<\/h2>\n<p>Follow the React tutorial series in order:<\/p>\n<ol>\n<li><a href=\"https:\/\/www.kindsonthegenius.com\/react\/01-react-introduction\/\">Lesson 1: React Tutorial \u2014 Introduction (2026)<\/a><\/li>\n<li><a href=\"https:\/\/www.kindsonthegenius.com\/react\/02-react-setup\/\">Lesson 2: React Setup \u2014 Create Your First App with Vite<\/a><\/li>\n<li><a href=\"https:\/\/www.kindsonthegenius.com\/react\/03-react-jsx-and-components\/\">Lesson 3: React JSX and Components \u2014 Build Your First UI<\/a><\/li>\n<li><a href=\"https:\/\/www.kindsonthegenius.com\/react\/04-react-state-usestate\/\">Lesson 4: React State and useState \u2014 Interactive UI (React 19+)<\/a><\/li>\n<li><strong aria-current=\"page\">Lesson 5: React useEffect \u2014 Side Effects and Data Fetching (React 19+)<\/strong><\/li>\n<li><a href=\"https:\/\/www.kindsonthegenius.com\/react\/06-react-forms\/\">Lesson 6: React Forms \u2014 Controlled Inputs and Validation (React 19+)<\/a><\/li>\n<li><a href=\"https:\/\/www.kindsonthegenius.com\/react\/07-react-router\/\">Lesson 7: React Router \u2014 Multi-Page Navigation (React 19+)<\/a><\/li>\n<li><a href=\"https:\/\/www.kindsonthegenius.com\/react\/\">\u2190 Back to React Tutorial hub<\/a><\/li>\n<\/ol>\n<\/nav>\n<p><!-- ktg-react-modern --><\/p>\n<div class=\"ktg-react-modern\" style=\"margin:1.5em 0;padding:1em;background:#eff6ff;border-left:4px solid #2563eb;border-radius:4px;\">\n<h4>React 19 Notes<\/h4>\n<p>Use <code>AbortController<\/code> to cancel in-flight fetches when components unmount. For data-heavy apps consider <strong>TanStack Query<\/strong>; for this series, <code>useEffect<\/code> + <code>fetch<\/code> teaches the fundamentals clearly.<\/p>\n<\/div>\n<p>This lesson explains <strong>React useEffect<\/strong> \u2014 the hook for side effects that run after render: fetching data, timers, DOM subscriptions, and syncing with external systems. You will fetch JSON from a public API and clean up resources correctly.<\/p>\n<p><strong>Prerequisites:<\/strong> Lessons 1\u20134, especially <a href=\"https:\/\/www.kindsonthegenius.com\/react\/04-react-state-usestate\/\">useState<\/a>. <strong>Estimated time:<\/strong> 50\u201360 minutes.<\/p>\n<h4 id=\"what-is-side-effect\">1. What Is a Side Effect?<\/h4>\n<p>A <strong>side effect<\/strong> is work that reaches outside the component&#8217;s render output: network requests, <code>localStorage<\/code>, <code>document.title<\/code>, WebSocket listeners, or <code>setInterval<\/code>. React expects render to be pure \u2014 effects belong in <code>useEffect<\/code>.<\/p>\n<figure style=\"margin:1.5em 0;text-align:center;\"><img decoding=\"async\" src=\"https:\/\/www.kindsonthegenius.com\/react\/wp-content\/uploads\/2026\/07\/05-react-useeffect-section-1.jpg\" alt=\"Fetching API data in a React application\" width=\"1200\" height=\"675\" loading=\"lazy\" style=\"max-width:100%;height:auto;border-radius:8px;border:1px solid #dee2e6;\" \/><figcaption style=\"font-size:0.85em;color:#666;margin-top:0.5em;\">Photo by <a href=\"https:\/\/unsplash.com\/@lukechesser?utm_source=kindsonthegenius&#038;utm_medium=referral\" rel=\"noopener noreferrer\" target=\"_blank\">Luke Chesser<\/a> on <a href=\"https:\/\/unsplash.com\/?utm_source=kindsonthegenius&#038;utm_medium=referral\" rel=\"noopener noreferrer\" target=\"_blank\">Unsplash<\/a><\/figcaption><\/figure>\n<h4 id=\"useeffect-syntax\">2. useEffect Syntax<\/h4>\n<pre><code class=\"language-jsx\">import { useEffect, useState } from 'react';\n\nfunction PageTitle({ title }) {\n  useEffect(() =&gt; {\n    document.title = title;\n  }, [title]);\n\n  return &lt;h1&gt;{title}&lt;\/h1&gt;;\n}\n<\/code><\/pre>\n<p>The second argument is the <strong>dependency array<\/strong>. React re-runs the effect when any dependency changes. An empty array <code>[]<\/code> runs once after mount (like <code>componentDidMount<\/code>).<\/p>\n<figure style=\"margin:1.5em 0;text-align:center;\"><img decoding=\"async\" src=\"https:\/\/www.kindsonthegenius.com\/react\/wp-content\/uploads\/2026\/07\/05-react-useeffect-section-2.jpg\" alt=\"JavaScript developer working with async data\" width=\"1200\" height=\"675\" loading=\"lazy\" style=\"max-width:100%;height:auto;border-radius:8px;border:1px solid #dee2e6;\" \/><figcaption style=\"font-size:0.85em;color:#666;margin-top:0.5em;\">Photo by <a href=\"https:\/\/unsplash.com\/@florianolv?utm_source=kindsonthegenius&#038;utm_medium=referral\" rel=\"noopener noreferrer\" target=\"_blank\">Florian Olivo<\/a> on <a href=\"https:\/\/unsplash.com\/?utm_source=kindsonthegenius&#038;utm_medium=referral\" rel=\"noopener noreferrer\" target=\"_blank\">Unsplash<\/a><\/figcaption><\/figure>\n<h4 id=\"fetch-example\">3. Fetch Data on Mount<\/h4>\n<pre><code class=\"language-jsx\">function UserList() {\n  const [users, setUsers] = useState([]);\n  const [loading, setLoading] = useState(true);\n  const [error, setError] = useState(null);\n\n  useEffect(() =&gt; {\n    async function loadUsers() {\n      try {\n        const res = await fetch('https:\/\/jsonplaceholder.typicode.com\/users');\n        if (!res.ok) throw new Error('Failed to fetch');\n        const data = await res.json();\n        setUsers(data);\n      } catch (err) {\n        setError(err.message);\n      } finally {\n        setLoading(false);\n      }\n    }\n    loadUsers();\n  }, []);\n\n  if (loading) return &lt;p&gt;Loading\u2026&lt;\/p&gt;;\n  if (error) return &lt;p&gt;Error: {error}&lt;\/p&gt;;\n\n  return (\n    &lt;ul&gt;\n      {users.map((user) =&gt; (\n        &lt;li key={user.id}&gt;{user.name}&lt;\/li&gt;\n      ))}\n    &lt;\/ul&gt;\n  );\n}\n<\/code><\/pre>\n<p>This pattern \u2014 loading, error, and data state \u2014 is standard in production React apps and frameworks like Next.js.<\/p>\n<h4 id=\"cleanup\">4. Cleanup Functions<\/h4>\n<p>Return a function from <code>useEffect<\/code> to clean up before the effect runs again or when the component unmounts:<\/p>\n<pre><code class=\"language-jsx\">useEffect(() =&gt; {\n  const id = setInterval(() =&gt; console.log('tick'), 1000);\n  return () =&gt; clearInterval(id);\n}, []);\n<\/code><\/pre>\n<p>Always clean up subscriptions, timers, and event listeners to prevent memory leaks \u2014 a core topic in any <strong>react useeffect tutorial<\/strong>.<\/p>\n<h4 id=\"dependency-pitfalls\">5. Dependency Array Pitfalls<\/h4>\n<ul>\n<li><strong>Missing deps<\/strong> \u2014 stale closures; ESLint <code>react-hooks\/exhaustive-deps<\/code> warns you<\/li>\n<li><strong>Object\/array deps<\/strong> \u2014 new reference every render causes infinite loops; memoize or lift state<\/li>\n<li><strong>No array<\/strong> \u2014 effect runs after every render (rarely what you want)<\/li>\n<\/ul>\n<h4 id=\"abort-fetch\">6. Abort Fetch on Unmount (React 19)<\/h4>\n<pre><code class=\"language-jsx\">useEffect(() =&gt; {\n  const controller = new AbortController();\n\n  fetch(url, { signal: controller.signal })\n    .then((res) =&gt; res.json())\n    .then(setData)\n    .catch((err) =&gt; {\n      if (err.name !== 'AbortError') setError(err.message);\n    });\n\n  return () =&gt; controller.abort();\n}, [url]);\n<\/code><\/pre>\n<p>Aborting prevents setting state on an unmounted component \u2014 especially important in React Strict Mode where effects run twice in development.<\/p>\n<h4 id=\"next\">7. Next Steps<\/h4>\n<p>Effects connect React to the outside world. Next you will build <strong>controlled forms<\/strong> with state and validation patterns used in real apps.<\/p>\n<p>Series: <a href=\"https:\/\/www.kindsonthegenius.com\/react\/04-react-state-usestate\/\">Lesson 4<\/a> \u00b7 <a href=\"https:\/\/www.kindsonthegenius.com\/react\/06-react-forms\/\">Lesson 6 \u2014 Forms<\/a><\/p>\n<h4 id=\"faq\">Frequently Asked Questions<\/h4>\n<p><strong>When should I use useEffect?<\/strong><br \/>\nUse it when you need to synchronize with something outside React&#8217;s render \u2014 APIs, browser APIs, third-party widgets, or timers.<\/p>\n<p><strong>Can I fetch data without useEffect?<\/strong><br \/>\nYes. React 19 and frameworks like Next.js support fetching in Server Components or with libraries like TanStack Query. <code>useEffect<\/code> fetch is still the standard pattern in client-only Vite SPAs.<\/p>\n<p><strong>Why does my useEffect run twice in development?<\/strong><br \/>\nReact Strict Mode intentionally double-invokes effects in development to surface cleanup bugs. Production behavior runs once per dependency change.<\/p>\n<p><!-- ktg-faq-schema --><br \/>\n<script type=\"application\/ld+json\">{\"@context\":\"https:\/\/schema.org\",\"@type\":\"FAQPage\",\"mainEntity\":[{\"@type\":\"Question\",\"name\":\"When should I use useEffect in React?\",\"acceptedAnswer\":{\"@type\":\"Answer\",\"text\":\"Use useEffect when you need to synchronize with something outside render \\u2014 APIs, browser APIs, timers, or third-party widgets.\"}},{\"@type\":\"Question\",\"name\":\"Why does useEffect run twice in development?\",\"acceptedAnswer\":{\"@type\":\"Answer\",\"text\":\"React Strict Mode intentionally double-invokes effects in development to surface missing cleanup logic. Production runs once per dependency change.\"}}]}<\/script><\/p>\n<p><!-- ktg-lesson-nav --><\/p>\n<nav class=\"ktg-lesson-nav\" aria-label=\"Lesson navigation\">\n<p><strong>Previous:<\/strong> <a href=\"https:\/\/www.kindsonthegenius.com\/react\/04-react-state-usestate\/\">Lesson 4: React State and useState \u2014 Interactive UI (React 19+)<\/a><\/p>\n<p><strong>Next:<\/strong> <a href=\"https:\/\/www.kindsonthegenius.com\/react\/06-react-forms\/\">Lesson 6: React Forms \u2014 Controlled Inputs and Validation (React 19+)<\/a><\/p>\n<\/nav>\n<p><!-- ktg-alkademy-cta --><\/p>\n<div class=\"ktg-alkademy-cta\">\n<p><strong>Want live React or frontend classes?<\/strong> Join <a href=\"https:\/\/www.alkademy.com\/courses\" target=\"_blank\" rel=\"noopener noreferrer\">Alkademy<\/a> for instructor-led React and JavaScript courses with hands-on projects.<\/p>\n<\/div>\n","protected":false},"excerpt":{"rendered":"<p>Updated July 4, 2026. Refreshed for React 19 and current SEO best practices. Table of Contents Follow the React tutorial series in order: Lesson 1: React Tutorial \u2014 Introduction (2026) Lesson 2: React Setup \u2014 Create Your First App with Vite Lesson 3: React JSX and Components \u2014 Build Your First UI Lesson 4: React [&hellip;]<\/p>\n","protected":false},"author":1,"featured_media":64,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"pagelayer_contact_templates":[],"_pagelayer_content":"","footnotes":""},"categories":[2],"tags":[],"class_list":["post-67","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-react-tutorials"],"_links":{"self":[{"href":"https:\/\/www.kindsonthegenius.com\/react\/wp-json\/wp\/v2\/posts\/67","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.kindsonthegenius.com\/react\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.kindsonthegenius.com\/react\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.kindsonthegenius.com\/react\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/www.kindsonthegenius.com\/react\/wp-json\/wp\/v2\/comments?post=67"}],"version-history":[{"count":3,"href":"https:\/\/www.kindsonthegenius.com\/react\/wp-json\/wp\/v2\/posts\/67\/revisions"}],"predecessor-version":[{"id":90,"href":"https:\/\/www.kindsonthegenius.com\/react\/wp-json\/wp\/v2\/posts\/67\/revisions\/90"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/www.kindsonthegenius.com\/react\/wp-json\/wp\/v2\/media\/64"}],"wp:attachment":[{"href":"https:\/\/www.kindsonthegenius.com\/react\/wp-json\/wp\/v2\/media?parent=67"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.kindsonthegenius.com\/react\/wp-json\/wp\/v2\/categories?post=67"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.kindsonthegenius.com\/react\/wp-json\/wp\/v2\/tags?post=67"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}