Skip to content

Instantly share code, notes, and snippets.

@kingluddite
Last active February 6, 2024 12:42
Show Gist options
  • Save kingluddite/205375e94c0cb7937797e504995b3301 to your computer and use it in GitHub Desktop.
Save kingluddite/205375e94c0cb7937797e504995b3301 to your computer and use it in GitHub Desktop.
Violation of React Hook Rule #2

Violation of React Hook Rule #2

Hooks should only be called from within components or custom hooks. They should never be called from regular Javascript functions.

Here's an example of a violation of the rule where a Hook is called from a regular JavaScript function instead of from within a component or a custom hook:

import React, { useState } from 'react';

// Regular JavaScript function outside of component
function myFunction() {
  // This violates the rule as useState is called from a regular JavaScript function
  const [count, setCount] = useState(0);
}

function MyComponent() {
  return (
    <div>
      <p>Hello, world!</p>
    </div>
  );
}

export default MyComponent;

In this example, the useState Hook is called from the myFunction regular JavaScript function instead of from within a component or a custom hook. This violates the rule that Hooks should only be called from within components or custom hooks.

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