Random Color TypeScript Function

Posted in category Code Snippets on
343 Words ~2 Minute Reading Time • Subscribe to receive updates on Code Snippets
Eric David Smith
Software Engineer / Musician / Entrepreneur
Random Color TypeScript Function by Eric David Smith

I use a lot of color in my projects. If you're looking for a simple function, don't install a package from NPM. Instead, first try to understand the problem, solution and of course the code before you reach for a new module.

A random color generator is a handy tool to have in your toolbox. Here's a simple function that returns a random color in TypeScript for use in React, Vue, Angular, or any other JavaScript project.

Simple Random Color Generator in TypeScript

export const randomColor = () => {
  const randomColor = Math.floor(Math.random() * 16777215).toString(16);
  return "#" + randomColor;

Better Random Color Generator in TypeScript

class ColorError extends Error {
  constructor(message?: string) {
    this.name = "ColorError";

export const randomColor = (): string => {
  const randomColor: number = Math.floor(Math.random() * 16777215);
  const colorString: string = "#" + randomColor.toString(16);

  // Check if the color is a valid 6-digit hexadecimal color
  if (!/^#[0-9A-F]{6}$/i.test(colorString)) {
    throw new ColorError(`Invalid color generated: ${colorString}`);

  return colorString;

Hooks for React

import { useState, useEffect } from "react";

const useRandomColor = () => {
  const [color, setColor] = useState<string>("#FFFFFF");

  useEffect(() => {
    try {
    } catch (error) {
      if (error instanceof ColorError) {
      } else {
        throw error;
  }, []);

  return color;

export default useRandomColor;


import React from "react";
import useRandomColor from "./useRandomColor";

const ColorfulComponent: React.FC = () => {
  const color = useRandomColor();

  return <div style={{ backgroundColor: color }}>Hello, world!</div>;

export default ColorfulComponent;

That's It!

Hope you enjoyed reading my blog and learning how to use this simople random color function in TypeScript. If you have any questions, please feel free to reach out to me on Twitter or LinkedIn.

Supporting My Work

Please consider Buying Me A Coffee. I work hard to bring you my best content and any support would be greatly appreciated. Thank you for your support!


Eric David Smith
Software Engineer / Musician / Entrepreneur
Code Snippets

Related Blog Posts

Scroll →

Blog Post Tags