2023/12/11

Ship it 4: Using my ai assistant to write utility React hooks.

TLDR; leverage AI to write utility functions and hooks in React instead of installing some random library.

Introduction

Sometimes, it's better to write a utility function than to install a large library just for one function. This is especially true when you want to know where your code is coming from or want to have control over it.

The Problem

I had a button in my application, and I wanted to add an icon next to it. When clicked, it would copy some content onto the user's clipboard.

The Solution

Instead of searching for a library that provides this functionality, I decided to see if my AI would write a hook for me that would copy some text to the user's clipboard.

You'll have to watch the video to see how easy it is to prompt your personal assistant right there in your code editor. But this is the code that it generated:

useClipboard.ts

const useClipboard = () => {
    const [isCopied, setCopied] = useState(false);
    
    const handleCopy = useCallback((text: any) => {
        if (typeof window === "undefined") return;
    
        try {
            window.navigator.clipboard.writeText(text);
            setCopied(true);
        } catch (err) {
            setCopied(false);
        }
    }, []);
    
    const handleReset = useCallback(() => setCopied(false), []);
    
    return { isCopied, onCopy: handleCopy, onReset: handleReset };
}

Using the Hook

Here's how you can use this hook in your components:

CopyButton.tsx

const CopyButton = ({ children }) => {
    const { isCopied, onCopy, onReset } = useClipboard();
    return (
        <button>
            {isCopied ? "Copied!" : children}
        </button>
    )
}

Conclusion

Writing custom hooks like this can be a great learning experience. You get to understand the underlying code and learn new things, like adding or removing event listeners from a media object. Plus, it's a great way to avoid bloating your project with unnecessary libraries.

That's it for this post. Ship it!