Building Your Learning Module...
Getting things ready for you!
Find videos you like?
Save to resource drawer for future reference!
Hooks are JavaScript functions, but they impose two additional rules. Following these rules ensures Hooks work correctly!
Don't call Hooks inside loops, conditions, or nested functions
Why? React relies on the order Hooks are called to preserve state between renders. Conditional Hooks break this order.
Call them from React components or custom Hooks only
Why? Hooks contain React-specific logic that only makes sense in React function components or custom Hooks.
eslint-plugin-react-hooks to automatically enforce these rules and catch mistakes!Hook order changes based on condition!
Hooks always called in same order!
All Hooks at top level, in React component
// ✅ Follows all Hook rules!
function UserProfile() {
// ✅ Rule 1: All Hooks at top level
const [name, setName] = React.useState('');
const [age, setAge] = React.useState('');
const [email, setEmail] = React.useState('');
const [isSubmitted, setIsSubmitted] = React.useState(false);
// ✅ Rule 2: In React function component
React.useEffect(() => {
document.title = name || 'Profile';
}, [name]);
// Event handlers can be anywhere
function handleSubmit(e) {
e.preventDefault();
setIsSubmitted(true);
setTimeout(() => {
setIsSubmitted(false);
}, 3000);
}
return (
<div className="container">
<h1>👤 User Profile</h1>
{isSubmitted && (
<div className="success-message">
✅ Profile saved successfully!
</div>
)}
<form onSubmit={handleSubmit} className="form">
<div className="field">
<label>Name</label>
<input
type="text"
value={name}
onChange={(e) => setName(e.target.value)}
required
className="input"
/>
</div>
<div className="field">
<label>Age</label>
<input
type="number"
value={age}
onChange={(e) => setAge(e.target.value)}
required
className="input"
/>
</div>
<div className="field">
<label>Email</label>
<input
type="email"
value={email}
onChange={(e) => setEmail(e.target.value)}
required
className="input"
/>
</div>
<button type="submit" className="btn-submit">
Save Profile
</button>
</form>
<div className="info">
💡 All Hooks declared at component top level!
</div>
</div>
);
}
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<UserProfile />);Loading preview...
Always call Hooks at the top level. Never inside loops, conditions, or nested functions.
Only call Hooks from React function components or custom Hooks.
React relies on Hook call order. Breaking the rules breaks this order and causes bugs.
Install the ESLint plugin to catch rule violations automatically during development.