React Hooks


Hooks added to React in version 16.8.

Hooks allow app components to have access to status and other React features. As a result, parts of the classroom are often no longer needed.


Although Hooks usually replace class parts, there are no plans to remove classes from React.



What is a Hook?

Hooks allow us to “connect” with React factors such as regions and life cycle patterns.


Example

Here is an example of a Hook. Don't worry if it doesn't make sense. We will go into more detail in the next section.

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'));

You must import Hooks from react.

Here we use the useState Hook to track app status.

State usually refers to application data or properties that need to be tracked.


Hook Rules

There are 3 rules for hooks:

  • Hooks can only be called inside React function components.
  • Hooks can only be called at the top level of a component.
  • Hooks cannot be conditional

Note: Hooks will not work in React class components.



Custom Hooks

If you have a smart idea that needs reuse in a few parts, you can create your own custom Hooks.