Sobes.tech
Middle+

Tell me about React hooks, rules of hooks

sobes.tech AI

Answer from AI

Hooks in React are functions that allow you to use state and other React features in functional components.

Main rules of hooks:

  1. Call hooks only at the top level of a component or custom hook. Do not call hooks inside loops, conditions, or nested functions to keep the call order stable between renders.
  2. Call hooks only from React functional components or custom hooks. Do not call hooks from regular JavaScript functions.

Example of using useState and useEffect:

import React, { useState, useEffect } from 'react';

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

  useEffect(() => {
    document.title = `You clicked ${count} times`;
  }, [count]);

  return (
    <button onClick={() => setCount(count + 1)}>
      Click me
    </button>
  );
}

Following the rules of hooks guarantees the correct operation of React's internal state and effect mechanisms.