DEV Community

Cover image for Side Effects: React, uh, Finds a Way
Charlotte Bush
Charlotte Bush

Posted on

Side Effects: React, uh, Finds a Way

Learning React after vanilla Javascript has been mind-bending. Working in React after weeks of trying to wrangle the DOM by hand is like realizing you can get a laugh with a clever movie reference, not having to do a whole long setup and punchline.

Image description
[1] “Welcome to Jurassic Park,” Imgflip, https://imgflip.com/i/7xmixa (accessed Aug. 31, 2023).

I was particularly fascinated during this phase of boot camp with the idea of functional components, or (to explain it to my two-weeks-younger self) what if functions, but on a scale that’s somehow smaller (one function per component makes things a ton more modular, and scope becomes easier to define) but also a whole lot more expansive.


Image description
[2] “That’s a big,” Imgflip, https://imgflip.com/i/7xm2h7 (accessed Aug. 31, 2023).

So, my adorable two-weeks-younger self wonders, what happens if you need to do something out of scope of the component? In vanilla JavaScript, you have a handy tool called a “closure” that lets you access an outer function’s scope from an inner function, like so:

function secretPassword() {
          const password = 'velociraptor93';
          return {
            guessPassword: function(guess) {
              if (guess === password) {
                return true;
              } else {
                return false;
              }
            }
          }
        }

        const passwordGame = secretPassword();
        passwordGame.guessPassword('clevergirl'); // false
        passwordGame.guessPassword('velociraptor93'); // true
Enter fullscreen mode Exit fullscreen mode

Apart from terrible password design, what this example shows is the closure function guessPassword getting exclusive access to the secret password. So what happens if you need to do something like this, outside of function scope, in a react component?

The short answer? Side effects. Whether you know it or not, you’ve been using these bad boys in React to ensure that anything you want done outside of the scope of the functional component gets done, from making an API call, to setting up a subscription, to manually changing the DOM. The “side” part often gets omitted, making their reach in our code easier to notice (I see you there, useEffect.)

I started wondering why these actions, which in vanilla Javascript were something of the main event, are now relegated to being classified as side effects. To understand why this linguistic snub of naming happens, we have to start thinking more about functions.

In our earlier Jurassic Park meme, we did think about react components as big functions, taking in inputs (usually props) and returning JSX (that piquant mix of HTML and JavaScript we’ve come to savor.) These functions can be thought of as pure if, given the same inputs, they deterministically produce the same result. So far, so testable, right? Here’s where sideEffects come in.

Side effects are thought of as “unpredictable” because they interact with the outside world, like an API, the DOM, or really anything outside a specific render of the functional component. That said, because we don’t necessarily control what’s outside of the component, the results are regarded as potentially:

Image description
[3]Ytimg.com, 2023. https://i.ytimg.com/vi/TRQp5x1iQEk/maxresdefault.jpg (accessed Aug. 31, 2023).

Enter, useEffect, which handles side effects in what would otherwise be pure React components. Much like a pack of raptors, performing a side effect (like a fetch get request) by itself would get in the way of our component’s rendering. To horribly paraphrase the OG Jurassic Park, you can do it, but you shouldn’t.

Image description
[4] “Jurassic Park Raptor,” Imgflip, https://imgflip.com/i/7xmhzy (accessed Aug. 31, 2023).https://imgflip.com/i/7xmhzy

useEffect(() => {
                fetch(raptorURL)
                  .then((r) => r.json())
                  .then((data) => setRaptorData(data));
              }, []);
Enter fullscreen mode Exit fullscreen mode

Using useEffect on a fetch request like this one allows us to get the benefits of the side effect (hello, API data!) while still preserving the purity of the component’s render. In this example, the component will render a second time once the data has returned. Both of these renders are still being mediated by the useEffect. Sounds like a clever girl to me!

Works Used:

  1. “The React useEffect Hook for Absolute Beginners,” freeCodeCamp.org, Mar. 01, 2022. https://www.freecodecamp.org/news/react-useeffect-absolute-beginners/ (accessed Aug. 31, 2023).

  2. “Using the Effect Hook – React,” legacy.reactjs.org. https://legacy.reactjs.org/docs/hooks-effect.html#:~:text=Data%20fetching%2C%20setting%20up%20a (accessed Aug. 31, 2023).

Cover Image:

[1]People.com, 2023. https://people.com/thmb/ZaDCClsPoc1buDSzf6biAdXhLJo=/1500x0/filters:no_upscale():max_bytes(150000):strip_icc():focal(999x0:1001x2)/jurassic-park-watn-tout-2000-26d6d3b1e08f458889f9497772ab477c.jpg (accessed Aug. 31, 2023).

Top comments (2)

Collapse
 
webjose profile image
José Pablo Ramírez Vargas • Edited

Working in React after weeks of trying to wrangle the DOM by hand is like realizing you can get a laugh with a clever movie reference, not having to do a whole long setup and punchline.

Oh boy! You'll fall out of your chair once you meet the uncrowned king: Svelte.

BTW, Svelte is learned in one day. 100% of it. Learn Svelte

Collapse
 
varlotte profile image
Charlotte Bush • Edited

I've heard that from dev friends, and I can't wait to get into it!