Introduction to React Hooks
Ever felt like React class components were a bit… clunky? You’re not alone. React Hooks came in like a superhero in version 16.8, making functional components smarter. Now, with version 19.1, things are even smoother and more efficient. If you’re new to React, learning useState
and useEffect
is the perfect starting point.
Understanding useState
What is useState
?
useState
is your tool to make components dynamic. It lets your function “remember” things—like a counter value, a checkbox toggle, or a text input. It’s like giving memory to your component.
const [state, setState] = useState(initialValue);
state
— the current value.setState
— the function to update that value.
How to Initialize State
const [count, setCount] = useState(0);
const [text, setText] = useState("");
Updating State in Functional Components
Use the setState
function you got from useState
.
setCount(count + 1);
setText("Hello React!");
Common Mistakes with useState
- Mistake: Updating state directly.
count = count + 1;
- Fix: Always use the updater function.
setCount(prev => prev + 1);
Practical Examples of useState
Creating a Counter
function Counter() {
const [count, setCount] = useState(0);
return (
<button onClick={() => setCount(count + 1)}>
Clicked {count} times
</button>
);
}
Toggling Dark/Light Mode
const [darkMode, setDarkMode] = useState(false);
Use it with a toggle switch or button and CSS class switching.
Handling Form Input with useState
const [email, setEmail] = useState("");
<input
type="email"
value={email}
onChange={(e) => setEmail(e.target.value)}
/>
Deep Dive into useEffect
What is useEffect
?
Think of useEffect
like side effect central. Anything that isn't rendering UI—like fetching data, setting timers, or syncing with outside systems—belongs here.
useEffect Syntax and Structure
useEffect(() => {
return () => {
};
}, [dependencies]);
When Does useEffect
Run?
- On mount (initial render)
- On update if dependencies change
- On unmount (cleanup)
Cleanup Function in useEffect
useEffect(() => {
const timer = setInterval(() => console.log("tick"), 1000);
return () => clearInterval(timer);
}, []);
Practical Examples of useEffect
Logging on Component Mount
useEffect(() => {
console.log("Component mounted");
}, []);
Fetching Data from an API
useEffect(() => {
fetch("https://api.example.com/data")
.then(res => res.json())
.then(data => setData(data));
}, []);
Listening to Window Resize
useEffect(() => {
const handleResize = () => console.log(window.innerWidth);
window.addEventListener("resize", handleResize);
return () => window.removeEventListener("resize", handleResize);
}, []);
The Dependency Array Explained
Why Dependencies Matter
This array tells React when to run the effect.
Empty Array vs No Array
[]
: Run only on mount- No array: Run on every render
Dynamic Dependencies
useEffect(() => {
console.log("Search term changed:", term);
}, [term]);
Combining useState
and useEffect
Building a Weather App (Basic)
Use useState
to store the city and weather data. Then, fetch data in useEffect
when the city changes.
Search Filter with Live Input
useState
: to hold input value.useEffect
: to filter/search as the user types.
Best Practices for Using Hooks
- Keep Hooks at the top of your components.
- Don’t conditionally call hooks (no if/else).
- Use custom hooks to reuse logic.
Debugging Common Errors
State Not Updating Immediately
React batches updates. Use useEffect
or logging to inspect changes correctly.
useEffect Runs Too Often
You likely missed adding a dependency.
Dependency Array Warnings
Always add variables/functions you use inside useEffect
to the dependency array—or disable linting with caution.
React 19.1 Update Notes
What’s New in 19.1 for Hooks?
- Improved performance for
useEffect
. - Better developer warnings for missing dependencies.
- Lazy initialization enhancements for
useState
.
Performance Improvements
React 19.1 optimizes re-renders, making useEffect
cleaner and more predictable.
Warnings and Error Messaging Changes
New warnings help catch infinite loops and untracked dependencies earlier.
Conclusion
If you’re just diving into React, learning useState
and useEffect
is your golden ticket. They unlock the magic of functional components and let you do more with less code. Once you get comfortable with these two, the rest of React feels way less intimidating.
FAQs
1. What is the difference between useState
and useEffect
?useState
manages data (state), while useEffect
handles side effects (fetching, timers, subscriptions).
2. Can we use multiple useState
and useEffect
in one component?
Absolutely! Use as many as you need.
3. Do Hooks replace Redux?
Not entirely. Hooks are great for local state; Redux is better for app-wide state management.
4. What happens if I forget the dependency array?
Your effect will run on every render, which can cause performance issues or infinite loops.
5. Is it okay to nest Hooks inside loops?
Nope. Always call Hooks at the top level of your component. Never inside loops or conditionals.
nice post
ReplyDelete