• Hooks are the new feature added in the React 16.8
  • It lets you use state and different React functions without writing a class.
  • React concepts does not replace your knowledge.
  • Inside classes do not work.
  • Hooks are the functions that “hook into” React state and lifecycle features from the function.

For example:

import React, { useState } from "react";
import ReactDOM from "react-dom";

function FavoriteColor() {
const [color, setColor] = useState("blue");

return (
<>
<h1>My favorite color is {color}!</h1>
<button
type="button"
onClick={() => setColor("yellow")}
>Yellow</button>
<button
type="button"
onClick={() => setColor("blue")}
>Blue</button>
<button
type="button"
onClick={() => setColor("orange")}
>Orange</button>
<button
type="button"
onClick={() => setColor("violet")}
>Violet</button>
</>
);
}

ReactDOM.render(<FavoriteColor />, document.getElementById('root'));

We must import Hooks from react. The useState is used to track the application state.

Rules of Hooks:

  • Call Hooks from React function components.
  • Call Hooks from Top level.
  • It cannot be conditional.

Categorized in: