Hi, Today I am going to describe one of the most important topics of React i.e, Hooks.
What is Hooks and How it works
Hooks were added to React in version 16.8.
Hooks give function components access to status and other React functions. Therefore, class components are generally unnecessary.
Example
import React, { useState } from "react";
import ReactDOM from "react-dom/client";
function FavoriteAnimal() {
const [color, setAnimal] = useState("horse");
return (
<>
<h1>My favorite animal is {animal}!</h1>
<button
type="button"
onClick={() => setColor("lion")}
>lion</button>
<button
type="button"
onClick={() => setColor("tiger")}
>tiger</button>
<button
type="button"
onClick={() => setColor("monkey")}
>monkey</button>
<button
type="button"
onClick={() => setColor("donkey")}
>donkey</button>
</>
);
}
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<FavoriteAnimal/>);
You have to import Hooks from react.
The state usually refers to application statistics or houses that need to be tracked.
Hook regulations
There are 4 rules for hooks:
- Hooks can only be called inner React feature components.
- Hooks can best be referred to as the pinnacle degree of an aspect.
- Hooks can not be conditional
- Hooks will not work in React class components.
Thanks.