--- type: video yt_id: VVU2YVRMdUlfajQtMHdpRFN6bWFQY3RRLmM4UjRDYmE3UFBZ videoId: c8R4Cba7PPY title: "useEffect Everything You Need To Know" date: "2022-09-29T14:00:33Z" slug: "useeffect-everything-you-need-to-know" image: name: "useeffect-everything-you-need-to-know.jpg" alt: "useEffect Everything You Need To Know" width: 1280 height: 720 status: 'published' description: "Learn everything you need to know about the useEffect hook and side effects in a react app." tags: ['nodejs', 'react', 'react js', 'javascript', 'hooks'] --- Learn everything you need to know about the useEffect hook and side effects in a react app. > **useEffect lets you synchronize things outside of the React tree according to our props and state.** > - https://overreacted.io/a-complete-guide-to-useeffect/#synchronization-not-lifecycle ## Chapters: * 0:00 Intro * 0:27 Component Lifecycle * 2:26 Side Effects * 6:52 useEffect * 13:03 Dependency Array * 17:34 [] componentDidMount * 23:45 Cleanup Functions * 25:59 Dependency Props * 29:50 Battery Status Component * 32:32 Event Listeners * 34:53 async useEffect * 39:14 Custom Hooks * 40:21 async await * 42:19 Summary ## Code https://github.com/Sam-Meech-Ward/useEffect --- ## [Components must be pure](https://beta.reactjs.org/learn/keeping-components-pure#side-effects-unintended-consequences) In React, components are functions that take input data and return output markup. It's important to keep the component function focused on rendering and not interacting with external systems like network requests or updating the window object. Any interaction with external systems is considered a side effect. ```jsx if (images.length === 0) { return 'No memes' } ``` This code inside of a components is absolutely fine because the logic here is only accessing state that exists within the component, and only returning markup that will be rendered to the dom. There is no interaction with an external system. But what about this code: ```jsx // Bad because it's in the top level of the component and is executed as part of the component rendering document.title = `You have ${images.length} memes` ``` This code interacts with an external system, the document, and is considered a side effect. To avoid running side effect code in the component function, we can create a function that causes side effects and call it later, such as when a user clicks a button. ```jsx // Good because it's inside a function that isn't executed as part of the component rendering const updateDocumentTitle = () => { document.title = `You have ${images.length} memes` } return ( // ...