Graph CMS
Dec 29, 2022

React Hooks

Hooks were added to React in version 16.8.

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

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

What is a Hook?

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

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 .

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><buttontype="button"onClick={() => setColor("blue")}>Blue</button><buttontype="button"onClick={() => setColor("red")}>Red</button><buttontype="button"onClick={() => setColor("pink")}>Pink</button><buttontype="button"onClick={() => setColor("green")}>Green</button></>);}const root = ReactDOM.createRoot(document.getElementById('root')); root.render(<FavoriteColor />);

Prashant Padhy

Prashant Padhy

Young , dumb & broke

Leave a Reply

Related Posts

Categories