Skip to content

Instantly share code, notes, and snippets.

@kingluddite
Created February 6, 2024 12:37
Show Gist options
  • Save kingluddite/53f0788cf2c467fb444099d3da5a17b7 to your computer and use it in GitHub Desktop.
Save kingluddite/53f0788cf2c467fb444099d3da5a17b7 to your computer and use it in GitHub Desktop.
Violation of React Hook Rule #1

Violation of React Hook Rule #1

  • Hooks should only be called from the top level of a component.
    • Never call Hooks from within loops, conditional or nested functions.

Here are some examples of violations of the rule where Hooks are called from within loops, conditional statements, or nested functions:

  1. Calling a Hook inside a loop:
import React, { useState } from 'react';

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

  for (let i = 0; i < 5; i++) {
    // This violates the rule as useState is called inside a loop
    useState(i);
  }

  return (
    <div>
      <p>Count: {count}</p>
      <button onClick={() => setCount(count + 1)}>Increment</button>
    </div>
  );
}

export default MyComponent;
  1. Calling a Hook inside a conditional statement:
import React, { useState } from 'react';

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

  if (count === 0) {
    // This violates the rule as useState is called inside a conditional statement
    useState(count);
  }

  return (
    <div>
      <p>Count: {count}</p>
      <button onClick={() => setCount(count + 1)}>Increment</button>
    </div>
  );
}

export default MyComponent;
  1. Calling a Hook inside a nested function:
import React, { useState } from 'react';

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

  function nestedFunction() {
    // This violates the rule as useState is called inside a nested function
    useState(count);
  }

  nestedFunction();

  return (
    <div>
      <p>Count: {count}</p>
      <button onClick={() => setCount(count + 1)}>Increment</button>
    </div>
  );
}

export default MyComponent;

In each of these examples, the useState Hook is being called within a loop, conditional statement, or nested function, which violates the rule that Hooks should only be called from the top level of a component.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment