In React, hooks must not be called conditionally or inside event handlers directly — they must always be called at the top level of a functional component or inside a custom hook. However, you can use state to control when the effect of a hook should happen.
Here’s how to trigger logic in a hook conditionally, such as after a button click or input change:
Correct Pattern: Use State and useEffect
Example 1: Hook logic triggered on button click
import React, { useState, useEffect } from 'react';
function MyComponent() {
const [clicked, setClicked] = useState(false);
useEffect(() => {
if (clicked) {
console.log("Button was clicked!");
// Put your hook-based logic here
}
}, [clicked]);
return (
<button onClick={() => setClicked(true)}>Click Me</button>
);
}
Example 2: Hook logic triggered by input value
import React, { useState, useEffect } from 'react';
function InputWatcher() {
const [inputValue, setInputValue] = useState('');
useEffect(() => {
if (inputValue.length > 3) {
console.log("Input is longer than 3 characters!");
// Trigger your hook logic here
}
}, [inputValue]);
return (
<input
type="text"
value={inputValue}
onChange={e => setInputValue(e.target.value)}
/>
);
}
Don’t Do This (Invalid Hook Usage)
if (someCondition) {
useEffect(() => { // ❌ This is not allowed!
// ...
}, []);
}
React needs to call hooks in the same order every render. Conditional calls break this rule and can lead to bugs.
