What is a React Side-Effect?

ยท

2 min read

In React, a side effect occurs when we do something that is beyond React.js in our React components, such as Web APIs like localStorage, these are not in the scope of React.

Here's a summary for those with limited time:

  • In React.js, side effects refer to anything beyond its scope. That is using native Web APIs, as they exist outside the React universe/scope.

  • Making external HTTPS requests is another example of a side effect.

  • Pushing a new item onto an array that was passed in as an argument is a side effect.

  • Changing the value of a closure-scoped variable is a side effect.

  • Typically, we handle React side effects with the useEffect hook from the React Hooks API.

  • However, for those with more time, please continue reading.

What is meant by "outside of the React scope"?

This refers to things that are not included in the React framework, such as the browser's - Third-party libraries or frameworks, such as jQuery or Bootstrap.

Third-party libraries or frameworks are not part of the React ecosystem.

By the way, these are valuable resources for constructing web applications. For further information, please refer to the official MDN website.

JQuery - https://jquery.com/

Bootstrap 5.3 - https://getbootstrap.com/docs/5.3/getting-started/introduction/

When we use any API in our React component such as the Bootstrap, we are creating side-effects.

For Example - You can create a side effect in your react component using the following code snippet -

Now that we have understood what is Side-Effect in React.

There is a question that arises is everything in React is a Side-Effect ?

ANSWER-

The Answer is NO!

Functions that execute without side effects are called "pure" functions.

What are Pure Functions?

  • Pure functions take an input value (a parameter or argument) and depending on that input, produce an output value, that's all.

  • Pure functions produce the same output given the same input every time.

  • They take in arguments, and they return values. Nothing else happens upon executing the function.

"Pure functions are predictable and reliable."

Reading tutorials are a great way to learn React, but there is no replacement for hands-on coding.

Enjoyed this tutorial?

Check out my profile -

Twitter ๐Ÿฆ- https://twitter.com/ritik_gupta1

Hashnode๐Ÿ“” - https://hashnode.com/@ritikgupta1

LinkedIn - https://www.linkedin.com/in/ritik-gupta-102225227/

I publish short tech tutorials on hashnode so consider subscribing to my Hashnode Blog.

Until next time โ€” keep coding while moving small steps forward on this coding adventure of yours.

But more importantly, stay focused!

Did you find this article valuable?

Support Ritik Gupta's team blog by becoming a sponsor. Any amount is appreciated!

ย