Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Вивчайте Rules of Using Hooks | Hooks
Introduction to React

bookRules of Using Hooks

There are certain rules we must follow while using Hooks to avoid surprises. For the hooks, there are two simple rules:

  1. Only call hooks at the top level;
  2. Only call hooks from React functions.

Top-level means directly inside the React component, and outside of any other code blocks, for example, loops or conditions. The following code shows valid and invalid cases:

function Main(props) { 
  // Correct
  const [ text, updateText ] = useState("Example"); 

  // Incorrect
  if(true) {
    const [ example, setExample ] = useState(0);
  }

  // Incorrect
  for(let i = 0; i < 10; i++) {
    useEffect(() => {
      console.log(text);
    });
  }
  return <p>{text}</p>; 
}

Apart from that, calling React hooks in functions other than React components is also invalid:

function randomFunction() {
  // Incorrect
  const [ count, setCount ] = useState(0);
  return 1;
}


function Main(props) { 
  // Correct, as this function represents a component
  const [ text, updateText ] = useState("Example"); 
  return <p>{text}</p>; 
}

Все було зрозуміло?

Як ми можемо покращити це?

Дякуємо за ваш відгук!

Секція 6. Розділ 4

Запитати АІ

expand

Запитати АІ

ChatGPT

Запитайте про що завгодно або спробуйте одне із запропонованих запитань, щоб почати наш чат

Awesome!

Completion rate improved to 2.7

bookRules of Using Hooks

Свайпніть щоб показати меню

There are certain rules we must follow while using Hooks to avoid surprises. For the hooks, there are two simple rules:

  1. Only call hooks at the top level;
  2. Only call hooks from React functions.

Top-level means directly inside the React component, and outside of any other code blocks, for example, loops or conditions. The following code shows valid and invalid cases:

function Main(props) { 
  // Correct
  const [ text, updateText ] = useState("Example"); 

  // Incorrect
  if(true) {
    const [ example, setExample ] = useState(0);
  }

  // Incorrect
  for(let i = 0; i < 10; i++) {
    useEffect(() => {
      console.log(text);
    });
  }
  return <p>{text}</p>; 
}

Apart from that, calling React hooks in functions other than React components is also invalid:

function randomFunction() {
  // Incorrect
  const [ count, setCount ] = useState(0);
  return 1;
}


function Main(props) { 
  // Correct, as this function represents a component
  const [ text, updateText ] = useState("Example"); 
  return <p>{text}</p>; 
}

Все було зрозуміло?

Як ми можемо покращити це?

Дякуємо за ваш відгук!

Секція 6. Розділ 4
some-alt