/    /  ReactJS- React Hooks

React Hooks

React Hooks are provide a new feature in the React 16.8 version. It allows you to react use state and other features of react component without writing a class. React Hooks are the functions that “hook into” React state and react lifecycle features from function react components. It does not work inside classes.

React Hooks are backward-compatible, it does not contain any breaking changes. Also, it does not replace your knowledge of React component concepts.

 

When to use a Hooks:

If you write a react function component, and then you want to add some react state to it, previously you do this by converting it to a class. But, now you can do it by using a Hook inside the existing react function component.

 

Rules of Hooks:
⦁ React Hooks can only be used inside React function components.
⦁ React Hooks can only be used at the top level of a react component.
⦁ Hooks cannot be conditional.

 

EXAMPLE:

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

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

  return (
   <>
    <h1>My favorite color is {color}!</h1>
    <button
     type="button"
     onClick={() => setColor("blue")}
    >Blue</button>
    <button
     type="button"
     onClick={() => setColor("red")}
    >Red</button>
    <button
     type="button"
     onClick={() => setColor("pink")}
    >Pink</button>
    <button
     type="button"
     onClick={() => setColor("green")}
    >Green</button>
  </>
 );
}

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

OUTPUT:

hooks