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.