What is a Hook?
Hooks were introduced to React in version 16.8.
Hooks enable function components to access state and other React capabilities. As a result, class components are largely obsolete.
Although hooks typically replace class components, there are no plans to eliminate classes within React.
What is a Hook?
Hooks let us “hook” into React features like state and lifecycle functions.
import React, { useState } from "react";
import ReactDOM from "react-dom/client";
function FavoriteColor() {
const [color, setColor] = useState("red");
return (
<>
My favorite color is {color}!
>
);
}
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render( );
Example:
This is an example of a hook. Don’t be concerned if it doesn’t make sense. We shall go into greater detail in the following section.
You must import Hooks from React.
We’re utilizing the useState Hook to maintain track of the application’s state.
State generally refers to application data or properties that must be tracked.
Hook Rules
There are three rules for hooks.
Hooks can only be used within React function components.
Hooks can only be invoked from the component’s top level.
Hooks cannot be conditional.
NOTE: Hooks do not operate in React class components.
Custom Hooks
If you have stateful logic that has to be reused across multiple components, you can create your own custom Hooks.
We’ll go into greater detail in the Custom Hooks section.