useRandomColor

React hook to generate random colors.

Add the hook via the CLI:

npx @novajslabs/cli add useRandomColor

Or copy and paste the code into your project:

import { useState } from 'react'

export const useRandomColor = () => {
  const [color, setColor] = useState('#000000')

  const generateColor = () => {
    const newColor =
      '#' +
      Math.floor(Math.random() * 16777215)
        .toString(16)
        .padStart(6, '0')

    setColor(newColor)
    return newColor
  }

  return { color, generateColor }
}

React 16.8 or higher

  • Name
    color
    Type
    string
    Description

    The currently generated color in hexadecimal format.

  • Name
    generateColor
    Type
    function
    Description

    Generates and returns a random color in hexadecimal format.

import { useRandomColor } from './hooks/useRandomColor'

function App() {
  const { color, generateColor } = useRandomColor()

  return (
    <div>
      <h1 style={{ color: color }}>Random color</h1>
      <button onClick={generateColor}>Generate new color</button>
    </div>
  )
}

export default App

Here are some use cases where this React hook is useful:

  • Creating a dynamic background color for a component in a digital art gallery website
  • Generating random colors for user avatars in a social media platform
  • Implementing a color-changing feature for a mood tracker or journaling app
  • Adding visual variety to UI elements such as buttons or cards in a web design tool
  • Developing a randomized color scheme generator for a design inspiration website