React/Next.js Explained: Closures, Immutable Updates, Async Handling #
I'll explain three important concepts for React/Next.js:
- closures in hooks,
- immutable updates,
- and async data handling.
We'll break them down in simple terms.
1. Closures in Hooks #
What is a closure?
Imagine you have a backpack (closure) that you carry around. You can put things in it (like variables) and then even when you leave your house (the function where you put the things), you still have the backpack with those things. So a closure is a function that "remembers" the environment (like variables) in which it was created.
How does it relate to React Hooks?
In React, when we use hooks like useState and useEffect, we often run into closures. Let's see an example:
function Counter() { const [count, setCount] = useState(0); useEffect(() => { const timer = setInterval(() => { console.log(count); // This will always log 0 for the first time? Why? setCount(count + 1); }, 1000); return () => clearInterval(timer); }, []); // Empty dependency array means this effect runs only once return <div>{count}</div>;}
The problem: The count inside the setInterval is the initial count (0) because the effect function was created when the component first rendered. It's like the backpack (closure) had a note that said count=0 and it never updates.
How to fix?
Use the functional update form of setCount:
setCount(prevCount => prevCount + 1);
This gets the latest state no matter what the closure has.
Another solution: Add count to the dependency array, but it will reset the interval on every render — not efficient. Functional update is better.
Key takeaway: Closures in hooks can cause stale state. Use functional updates or manage dependencies properly.
2. Immutable Updates #
What is immutability?
Immutability means not changing the original data. Instead, you make a copy and modify that.
Why is it important in React?
React checks if state has changed using shallow comparison. If you change the original object (mutate), React might miss the change.
Example of mutation (bad):
const [user, setUser] = useState({ name: "Alice", age: 15 });user.age = 16;setUser(user); // Won't re-render: same object reference
Correct way (immutable update):
setUser({ ...user, age: 16 }); // New object
For arrays:
// AddsetFruits([...fruits, 'orange']); // RemovesetFruits(fruits.filter(fruit => fruit !== 'apple')); // UpdatesetFruits(fruits.map(fruit => fruit === 'banana' ? 'mango' : fruit));
Why does React care?
React only re-renders when it sees a new object reference.
Key takeaway: Never mutate state. Use ..., map, filter, slice to create new versions.
3. Async Data Handling #
What is async?
Async means "not at the same time". In JavaScript, things like API calls are async — they take time.
In React/Next.js:
We often fetch data using useEffect or special Next.js functions like getStaticProps.
Example with useEffect:
function UserProfile() { const [user, setUser] = useState(null); useEffect(() => { async function fetchUser() { try { const response = await fetch('/api/user'); const data = await response.json(); setUser(data); } catch (error) { console.error('Failed to fetch user:', error); } } fetchUser(); }, []); if (!user) return <div>Loading...</div>; return <div>Hello, {user.name}</div>;}
Important tips:
- Always show a loading state
- Use try/catch to handle errors
- Clean up if component unmounts:
useEffect(() => { let isMounted = true; async function fetchData() { const data = await someFetch(); if (isMounted) setData(data); } fetchData(); return () => { isMounted = false; };}, []);
In Next.js (page-level fetch):
export async function getStaticProps() { const res = await fetch('https://api.example.com/data'); const data = await res.json(); return { props: { data }, };}
Key takeaway: Always handle loading, errors, and cleanup for async ops.
🔁 Summary #
- Closures in Hooks – Functions remember old values. Use functional updates like
setCount(prev => prev + 1)to get fresh state. - Immutable Updates – Never change state directly. Always copy objects/arrays when updating.
- Async Handling – Use
async/await, handle loading and error states, and clean up properly.
Master these, and you’ll avoid 90% of common React/Next.js bugs
Feel free to ask me any questions thought : E-Mail


Loading discussion...