Skip to content
Related Articles
Get the best out of our app
GeeksforGeeks App
Open App

Related Articles

How to generate random colors by using React hooks ?

Improve Article
Save Article
Like Article
Improve Article
Save Article
Like Article

In web development, colors play a vital role in creating visually appealing and engaging user interfaces. As a React developer, you may often find yourself needing to generate random colors dynamically. In this article, we will explore how to achieve this using React hooks, a powerful feature introduced in ReactJs.

We are going to make a react custom hook for generating random colors.


Approach: Basically, if we are familiar with React , then we all have already used react custom hooks(like useState, useEffect , useContext etc.). We can also make our custom react hooks and can use it wherever we want. So there’s a small code for generating random colors. Here we will be making a random color generator custom hook (in our custom hook file), here we will make a function for changing color called (generateColor) , and we will be passing color and generate color as return. Then we will use this in our App.js by destructuring and will use that generate color as an onClick event function for a button through which we will change the color of our window.

Creating react application:

Step 1: Go to your command prompt and write the below command to create a react app.

npx create-react-app <YOUR_APP_NAME>

Step 2: Then go to your app folder by typing the below command


Project Structure: Our folder structure should be like this.

Folder structure

Step 3: Make a separate file useGenerateRandomColor.js in your src folder and use the below code :


import { useState } from 'react';
const useGenerateRandomColor = () => {
    const [color, setColor] = useState("")
    const generateColor = () => {
    return { color, generateColor };
export default useGenerateRandomColor;

Step 4: Now go to src/App.js and paste the below code to use our random color generator custom hook.


import "./App.css";
import useGenerateRandomColor
    from "./useGenerateRandomColor";
function App() {
    const { color, generateColor }
        = useGenerateRandomColor();
    return (
                height: "100vh",
                width: "100vw",
                backgroundColor: "#" + color,
                display: "flex",
                justifyContent: "center",
                alignItems: "center",
                    padding: "40px",
                    borderRadius: "10px",
                        "linear-gradient(to top, #a8edea 0%, #fed6e3 100%)",
                    fontSize: "larger",
                Generate random color
export default App;

Now we are good to go with our react app .

Step to run the application: Run the following command to start your app in your localhost:3000.

npm start


My Personal Notes arrow_drop_up
Last Updated : 05 Jun, 2023
Like Article
Save Article
Similar Reads
Related Tutorials