DEV Community

kanaga vimala
kanaga vimala

Posted on

Today i Learned what is Hooks and why used hooks.

What is a Hook?

Hooks allow function components to have access to state and other React features. Because of this, class components are generally no longer needed.

Hooks allow us to "hook" into React features such as state and lifecycle methods.

Why used Hooks?

Although Hooks generally replace class components, there are no plans to remove classes from React.

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/client";

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

return (
<>

My favorite color is {color}!


type="button"
onClick={() => setColor("blue")}
>Blue
type="button"
onClick={() => setColor("red")}
>Red
type="button"
onClick={() => setColor("pink")}
>Pink
type="button"
onClick={() => setColor("green")}
>Green
</>
);
}

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render();

You must import Hooks from react.

Here we are using the useState Hook to keep track of the application state.

State generally 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
Enter fullscreen mode Exit fullscreen mode

Note: Hooks will not work in React class components.

React useState Hook

The React useState Hook allows us to track state in a function component.

State generally refers to data or properties that need to be tracking in an application.
Import useState

To use the useState Hook, we first need to import it into our component.
Example:

At the top of your component, import the useState Hook.

import { useState } from "react";

Notice that we are destructuring useState from react as it is a named export.

Top comments (0)

Some comments may only be visible to logged-in visitors. Sign in to view all comments.