How to generate random colors by using React hooks ?
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.
Step 3: Make a separate file useGenerateRandomColor.js in your src folder and use the below code :
Step 4: Now go to src/App.js and paste the below code to use our random color generator custom hook.
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.