loading

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.


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 (
                <>
      <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>
                </>
                );
        }
        const root = ReactDOM.createRoot(document.getElementById('root'));
        root.render(<FavoriteColor />);
				
			

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.

Share this Doc

What is a Hook?

Or copy link

Explore Topic