avatarNivedha Duraisamy

Summary

The webpage outlines four methods for adding external JavaScript files in React applications, ranging from using npm packages like react-script-tag and React Helmet to manual DOM manipulation and React Hooks.

Abstract

The article "4 Ways to Add External JavaScript Files in React" provides a comprehensive guide for developers who need to incorporate external JavaScript libraries into their React projects. It begins by acknowledging the necessity of external scripts despite the abundance of npm packages. The author then delves into various techniques, starting with the react-script-tag package, which is beginner-friendly and supports universal rendering. Next, the article introduces React Helmet, a component that manages changes to the document head and supports server-side rendering. For developers who prefer not to add extra packages, the DOM method is presented as a more hands-on approach. The article also covers the use of React Hooks, particularly useEffect, to dynamically append and clean up scripts, and suggests creating custom Hooks for reusable logic. The author emphasizes the importance of removing scripts on page redirection or reload to prevent redundant execution.

Opinions

  • The author suggests that React Helmet is not the best choice if the sole purpose is to use script tags due to its heavier weight compared to react-script-tag.
  • For more experienced developers, manual DOM manipulation is recommended over adding additional packages, to avoid bulking up the application.
  • The use of React Hooks, such as useEffect, is encouraged for fans of functional components, providing a modern and efficient way to handle side effects, including script injection and cleanup.
  • Custom Hooks are advocated for encapsulating the logic for script importation, promoting code reusability and maintainability.
  • The article implies that developers should be mindful of when to load scripts, especially in single-page applications, to ensure they are not unnecessarily reloaded or executed.

4 Ways to Add External JavaScript Files in React

React Hooks and other methods

Photo by Kelly Sikkema on Unsplash

Despite the wide availability of npm packages, at times, we might need to rely on a few external libraries that require us to import some JS files.

For features used across the application, we can simply add JS files to head using the <script> tag in our global index.html file.

However, for the features that are used in specific components, this makes no sense. Since React doesn’t support the <script> tag in Component, here are a few ways of appending JS files to specific components.

React-script-tag

This is the easiest way of loading JS files for a beginner.

React-script-tag is an npm package that provides a React <script> tag that supports universal rendering. All standard <script> attributes like async, src, type, and defer are supported, including onLoad and onError callbacks.

import ScriptTag from 'react-script-tag';
const Demo = props => (
<ScriptTag type="text/javascript" src="/path/to/resource.js" />
)

We also have an isHydrating flag, which is a boolean value. It defaults to false and must be true if the client is hydrate()ing the server render.

You can read more about hydrate() in the React docs.

React Helmet

Helmet is a React component that manages all your changes to the document head. It is another simple, beginner-friendly package that supports both server-side and client-side rendering.

Helmet takes plain HTML tags and outputs plain HTML tags.

Note: React Helmet is heavier than react-script-tag, so I wouldn’t recommend using it if your only purpose is to use script tags.

DOM Method

Though the above solutions are simple to achieve, it requires us to add additional packages that might bulk up our application. If you have some experience coding, then you can do:

If you are appending JS files in more than one component, it is best to have a custom file that returns a function to do this.

In your component:

If you don’t want to retain the appended JS file on page redirection/reload, you should remove the script in the componentDidUnmount lifecycle method. To achieve this:

And in your component:

React Hooks

If you are a fan of Hooks in React, then useEffect is a great way to append external JS files. You can read my article on using the Effect Hook.

To give a gist useEffect is similar to componentDidMount and componentDidUpdate life cycle methods in React class components.

If your effect returns a function, React will run it when it is time to clean up, basically the componentDidUnmount lifecycle method. This is where we will remove the appended script.

React allows us to build custom Hooks, which let us extract component logic into reusable functions. The logic to append an external JS file to a component could be stored as a custom Hook as below:

Which could be used in components as below:

import importScript from 'customHooks/importScript';
const Demo = props => {
  importScript("/path/to/resource.js");
}

Resources

Thanks for reading!

React
Script
JavaScript
Reactjs
Programming
Recommended from ReadMedium