Hooks FundamentalsBeginner
1Question 1 of 1
javascriptHow do useState and useEffect work and what are the rules of React Hooks?
Explanation & Concept
Hooks allow functional components to manage local state and lifecycle side effects without writing class components.
• `useState`: Declares a state variable and an updater function that triggers re-rendering when state changes. • `useEffect`: Runs side effects (API calls, DOM manipulation, event listeners) after the component renders.
**Rules of Hooks**: 1. Only call hooks at the **top level** of components (never inside loops, conditions, or nested functions). 2. Only call hooks from React function components or custom hooks.
Code Example
javascript
import { useState, useEffect } from "react";
export function CounterTimer() {
const [count, setCount] = useState(0);
useEffect(() => {
// Set up timer side effect
const interval = setInterval(() => {
setCount((prev) => prev + 1);
}, 1000);
// Clean-up function runs when component unmounts or before re-running effect
return () => clearInterval(interval);
}, []); // Empty dependency array = runs once on mount
return (
<div className="p-4 border rounded">
<p>Seconds elapsed: {count}</p>
<button onClick={() => setCount(0)}>Reset</button>
</div>
);
}How It Works & Key Takeaways
The returned cleanup function inside `useEffect` prevents memory leaks by reliably clearing the interval timer when the component unmounts.
Mock Test · 1 Questions · Optional
Ready for Performance & Memoization?
Take a quick test to evaluate yourself, or move straight to the next module.
Beginner1 questions