React Hooks are functions that allow functional components to have state, lifecycle methods, and other React features. They were introduced in React 16.8 to provide a way to use state and other React features in functional components instead of class components.
Rules for Using Hooks:
- Only use Hooks at the top level of a functional component or a custom hook.
- Only call Hooks from functional components or custom hooks; do not call them in regular JavaScript functions.
- Hooks should be called in the same order every time the component renders.
- Hooks cannot be called conditionally; they should be called in the same order every render.
Code :
import React, { useState } from 'react';
const ColorSelector = () => {
const [selectedColor, setSelectedColor] = useState(null);
const handleColorClick = (color) => {
setSelectedColor(color);
};
return (
<div>
<h2>Selected Color: {selectedColor}</h2>
<button onClick={() => handleColorClick('Red')}>Red</button>
<button onClick={() => handleColorClick('Blue')}>Blue</button>
<button onClick={() => handleColorClick('Green')}>Green</button>
<button onClick={() => handleColorClick('Yellow')}>Yellow</button>
</div>
);
};
export default ColorSelector;
Now Import ColorSelector in index.js
import React from 'react';
import ReactDOM from 'react-dom';
import ColorSelector from './ColorSelector';
ReactDOM.render(
<React.StrictMode>
<ColorSelector />
</React.StrictMode>,
document.getElementById('root')
);