Loading

React JS

What is a React Hook?. The Complete React JS Developer Course 2022 [Videos].

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. Dont worry if it doesnt 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 (
    <>
      <h2>My favorite color is {color}!</h2>
      <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 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

Note: Hooks will not work in React class components.

See All

Comments (480 Comments)

Submit Your Comment

See All Posts

Related Posts

React JS / Youtube

What is react JS vs react native?

React is the most popular javascript library for building user interfaces. It is fast, flexible and it also has a strong community sitting online to help you every time. The coolest thing about React is its based on components, you break down your complex code into individual pieces i.e components and that helps developers in organizing their code in a better way. A lot of companies are moving to React and thats the reason most of the beginners and experienced developers also expanding their knowledge learning this library.
27-jan-2021 /2 /480

React JS / Youtube

The Top 5 Programming Languages in 2022 to get a job.

The Top 5 Programming Languages in 2022 to get a job -React JS and React Native Tutorial The Complete Developer Course Part#2 [Urdu/Hindi]
27-jan-2021 /2 /480

React JS / Youtube

What is props in React?

Props is simply shorthand for properties. Props are how components talk to each other and the data flow is immutable. Props are passed down the component tree from parent to children and vice versa.
27-dec-2020 /2 /480