DEV Community

rashidpbi
rashidpbi

Posted on

๐Ÿ”„ React Lifecycle, useEffect, and Whatโ€™s Really Happening in Next.js

When I started learning React and Next.js, I wanted to understand not just how to use hooks like useEffect, but what's really happening under the hood. Here's a beginner-friendly breakdown of what I learned โ€” and how it ties together with core JavaScript concepts.

๐Ÿงฉ Understanding useEffect with React Lifecycle

React components go through three main phases:

  • Mounting โ€“ inserted into the DOM
  • Updating โ€“ re-render due to props/state change
  • Unmounting โ€“ removed from the DOM

In functional components, useEffect acts as a replacement for old class lifecycle methods like componentDidMount, componentDidUpdate, and componentWillUnmount.

useEffect(() => {
  // runs once on mount
  return () => {
    // cleanup before unmount
  };
}, []);
Enter fullscreen mode Exit fullscreen mode

โœ… Common patterns

Purpose useEffect usage
Run once on mount useEffect(() => {...}, [])
Run on update useEffect(() => {...}, [deps])
Cleanup return () => {...} inside useEffect

Think of useEffect as a way to handle side effects (like API calls, subscriptions) after the DOM is updated.

โš ๏ธ Can I Use useState Inside useEffect?

No โ€” calling useState() inside useEffect() violates the Rules of Hooks.

โŒ Invalid

useEffect(() => {
  const [count, setCount] = useState(0); // โŒ Not allowed
}, []);
Enter fullscreen mode Exit fullscreen mode

โœ… Valid

const [count, setCount] = useState(0);
useEffect(() => {
  setCount(5); // โœ… Allowed
}, []);
Enter fullscreen mode Exit fullscreen mode

๐Ÿ” JavaScript Concepts Behind Next.js

Next.js is a powerful React framework, but it's built on top of vanilla JavaScript and Node.js. Here are the core JS concepts powering it:

Concept Why It Matters
import/export Modular code structure
async/await & Promises Data fetching & API routes
Closures Powering hooks and handlers
Array methods (map, filter) Rendering lists
Spread/Rest & Destructuring Cleaner state updates
File system APIs Routing and API creation
Environment variables App config (.env.local)
Node.js concepts Server-side logic in API routes

The more you understand JavaScript fundamentals, the easier Next.js becomes.

๐Ÿง  Final Thoughts

Learning React and Next.js by diving into the underlying JS helped me gain real clarity. Instead of memorizing patterns, I now understand why things work โ€” and when to use them.

If you're a beginner, my tip: spend time understanding hooks, lifecycle, and JS concepts like promises, closures, and modules. It pays off quickly ๐Ÿš€

Top comments (0)