React Hooks Deep Dive: Part 1 - useState and useEffect
Published on
by Nguyễn Công Dũngreacthooksjavascripttutorial
React Hooks Deep Dive: Part 1 - useState and useEffect
This is the first part of a series exploring React Hooks in depth. In this post, we’ll cover the two most fundamental hooks: useState and useEffect.
useState Hook
The useState hook allows you to add state to functional components:
import { useState } from 'react';
function Counter() {
const [count, setCount] = useState(0);
return (
<div>
<p>Count: {count}</p>
<button onClick={() => setCount(count + 1)}>Increment</button>
</div>
);
}Key Points
- State can be any type: number, string, object, array, etc.
- The setter function can accept a value or a function
- State updates trigger re-renders
useEffect Hook
The useEffect hook lets you perform side effects in functional components:
import { useEffect, useState } from 'react';
function UserProfile({ userId }) {
const [user, setUser] = useState(null);
useEffect(() => {
fetch(`/api/users/${userId}`)
.then(res => res.json())
.then(data => setUser(data));
}, [userId]); // Dependency array
if (!user) return <div>Loading...</div>;
return <div>{user.name}</div>;
}Dependency Array
- Empty array
[]: Run once on mount - No array: Run on every render
- With dependencies: Run when dependencies change
Coming Next
In Part 2, we’ll explore useContext, useReducer, and custom hooks. Stay tuned!