useScript
React hook to load a script.
Add the hook via the CLI:
sh
npx @novajslabs/cli add useScript
sh
npx @novajslabs/cli add useScript
sh
pnpm dlx @novajslabs/cli add useScript
Or copy and paste the code into your project:
ts
import { useEffect, useState } from "react";
export const useScript = (url: string) => {
const [loading, setLoading] = useState(true);
const [error, setError] = useState<string | null>(null);
useEffect(() => {
const script = document.createElement("script");
script.src = url;
script.async = true;
script.onload = () => {
setLoading(false);
};
script.onerror = () => {
setError(`Failed to load script ${url}`);
setLoading(false);
};
document.body.appendChild(script);
return () => {
document.body.removeChild(script);
};
}, [url]);
return { loading, error };
};
js
import { useEffect, useState } from "react";
export const useScript = (url) => {
const [loading, setLoading] = useState(true);
const [error, setError] = useState(null);
useEffect(() => {
const script = document.createElement("script");
script.src = url;
script.async = true;
script.onload = () => {
setLoading(false);
};
script.onerror = () => {
setError(`Failed to load script ${url}`);
setLoading(false);
};
document.body.appendChild(script);
return () => {
document.body.removeChild(script);
};
}, [url]);
return { loading, error };
};
Requirements
React 16.8 or higher
Parameters
url required
Type: string
The URL of the script to load.
Return values
loading
Type: boolean
Indicates whether the script is currently being loaded (true
) or not (false
).
error
Type: string | null
Error message if the script fails to load, otherwise null
.
Example
tsx
import { useScript } from "./hooks/useScript";
const App = () => {
const { loading, error } = useScript("https://cdn.tailwindcss.com");
if (loading) return <div>Loading Tailwind CSS...</div>;
if (error) return <div>Error loading Tailwind CSS: {error}</div>;
return <div>Tailwind CSS loaded successfully!</div>;
};
export default App;
Use cases
Here are some use cases where this React hook is useful:
- Loading live chat services
- Embedding map services
- Dynamic loading of social media widgets