DEV Community

Deva I
Deva I

Posted on

React hooks

Definition of React hooks :

React Hooks are special functions introduced in React 16.8 that allow you to use state and other React features (like lifecycle methods) inside functional components without writing a class.

Why hooks matter :

Before Hooks, functional components were "stateless"β€”they could only receive props and render UI.

The Two Golden Rules :

1.Only call Hooks at the top level: Do not call them inside loops, conditions, or nested functions.

2.Only call Hooks from React functions: Use them only within React functional components or your own custom Hooks.

Types of Hooks :

State hooks :
useState

UseReducer(TBD)

Effect hooks:(TBD)
useEffect
useLayoutEffect

Context & Effect hooks :(TBD)
useContext
useRef

Performance Hooks :(TBD)
useMemo
useCallback

UseState :

In React, useState is a built-in Hook that allows you to add state variables to functional components

When you call useState, it returns an array containing two items. the current state value and a setter function to update it.

import { useState } from "react";

function Counter() {
  const [count, setCount] = useState(0);

  return (
    <div>
      <p>You clicked {count} times</p>

      <button onClick={() => setCount(count + 1)}>
        Click me
      </button>
    </div>
  );
}
export default Counter;
Enter fullscreen mode Exit fullscreen mode

Top comments (0)