DEV Community

Cover image for Demystifying React's Inner Workings: A Visual Journey Through React's Lifecycle with TypeScript (2024 Edition)
Vishal Yadav
Vishal Yadav

Posted on

Demystifying React's Inner Workings: A Visual Journey Through React's Lifecycle with TypeScript (2024 Edition)

Hey there, React enthusiasts! πŸ‘‹ Ever felt like React was performing magic behind the scenes? Well, you're not alone! Today, we're going to pull back the curtain and explore the fascinating inner workings of React. Whether you're a newbie or a seasoned pro, this guide will help you visualize React's lifecycle and understand how TypeScript can supercharge your development. Let's dive in!

The Initial Render Phase: Where the Magic Begins

Picture this: you've just created a shiny new React component. What happens next? Let's break it down step by step.

Step 1: Your React Component Takes Center Stage

It all starts with your React component. Here's a simple example using TypeScript:

import React from 'react';

interface HelloProps {
  name: string;
}

const HelloComponent: React.FC<HelloProps> = ({ name }) => {
  return <h1>Hello, {name}!</h1>;
};

export default HelloComponent;
Enter fullscreen mode Exit fullscreen mode

This little component is about to embark on an exciting journey!

Step 2: React's Virtual DOM Wizardry

When your component first renders, React conjures up a lightweight copy of the DOM, known as the virtual DOM. It's like React's own personal sketch pad.

import React from 'react';
import ReactDOM from 'react-dom';
import HelloComponent from './HelloComponent';

ReactDOM.render(<HelloComponent name="World" />, document.getElementById('root'));
Enter fullscreen mode Exit fullscreen mode

Pro tip: While this code still works, React 18 introduced the new createRoot API for even better performance. Consider updating your code to:

import { createRoot } from 'react-dom/client';

const root = createRoot(document.getElementById('root'));
root.render(<HelloComponent name="World" />);
Enter fullscreen mode Exit fullscreen mode

Step 3: From Virtual to Reality

React then takes this virtual DOM and transforms it into the actual DOM that your browser displays. It's like bringing a blueprint to life!

Step 4: Time for Some Action!

Now your app is live, and users can interact with it. Click a button, type in a form, or scroll – the fun begins!

The State Update Phase: React's Time to Shine

Alright, so your app is up and running. But what happens when something changes? That's where the state update phase comes in, and it's where React really flexes its muscles.

Step 1: Change is in the Air

Let's say a user clicks a button in your app. This triggers a state change. Here's a simple counter example:

import React, { useState } from 'react';

const Counter: React.FC = () => {
  const [count, setCount] = useState(0);

  return (
    <div>
      <p>You clicked {count} times</p>
      <button onClick={() => setCount(count + 1)}>Click me</button>
    </div>
  );
};

export default Counter;
Enter fullscreen mode Exit fullscreen mode

Step 2: React Springs into Action

When setCount is called, React kicks off its update process. But here's the cool part – it doesn't immediately update the DOM. React is smarter than that!

Step 3: The Great Reconciliation

React compares the new virtual DOM with the previous one. This process is called reconciliation, and it's like a game of spot the difference.

  • Diffing Algorithm: React uses a super-efficient algorithm to figure out what's changed.
  • Minimal Updates: It then calculates the smallest number of changes needed to update the actual DOM.

Step 4: Only the Essentials

React updates only the parts of the DOM that have actually changed. This is why React is so fast – it doesn't waste time updating things that haven't changed.

Step 5: The Big Reveal

The browser DOM gets updated, and voila! The user sees the new state of your app.

Leveling Up with TypeScript

Now, let's talk about adding TypeScript to the mix. It's like giving your React app superpowers!

Type Safety: Catching Bugs Before They Happen

TypeScript helps you catch errors before they sneak into production. Here's how you can use it with React:

interface CounterProps {
  initialCount: number;
}

const Counter: React.FC<CounterProps> = ({ initialCount }) => {
  const [count, setCount] = useState(initialCount);

  return (
    <div>
      <p>You clicked {count} times</p>
      <button onClick={() => setCount(count + 1)}>Click me</button>
    </div>
  );
};
Enter fullscreen mode Exit fullscreen mode

IDE Superpowers

With TypeScript, your IDE becomes a coding wizard. You get:

  • Autocompletion that actually works
  • Refactoring tools that understand your code
  • Inline documentation for your components and props

Wrapping Up: Your React Journey Continues

Understanding React's inner workings is like learning the secret handshake of an exclusive club. You now know how React efficiently updates the DOM, keeping your apps fast and smooth.

Remember, React is constantly evolving. The React team is always working on new features to make our lives easier. Keep an eye out for updates and new features in future React versions!

So, what's your favorite part of React's lifecycle? Have you had any "aha!" moments while working with React and TypeScript? Drop a comment below and let's geek out together!

Happy coding, and may your components always render flawlessly! πŸš€πŸ’»

Top comments (4)

Collapse
 
m3rashid profile image
MD Rashid Hussain

Convince me this article is not AI generated
Its disappointing to see such content.
Please take it as a constructive criticism bro, I have seen the transition of react from being a bloated shit, to something actually good and seeing these content hurt me, it actually hurts

Collapse
 
shishantbiswas profile image
Shishant Biswas

Thanks for sharing Vishal, I've recently started using typescript for my projects this helps a lot, thank you

Collapse
 
brense profile image
Rense Bakker

Between step 2 and step 3 React will rerender the whole tree of components in which the state changed. This step is what's often the biggest performance issue in React apps, because people fail to memoize internal state and callbacks in a component. React compiler will auto optimize this step but imho people should still learn why it's important to memoize things, because not memorizing can lead to strange app behavior, performance problems, or even bugs.

Collapse
 
thunder6230 profile image
thunder6230 • Edited

It rerenders every component on state changes and even the children components. React does is it a very fast but not efficient way. To avoid this nested rerenders you should introduce memoization technics like useMemo for calculated values for expensive getters, usecallbacks to not recreate every functions on rerendering and memo to memoize a component. Luckily the new react 19 with its brand new react compiler will do that for you, but it's still good to know what it does under the hood πŸ™‚

Some comments may only be visible to logged-in visitors. Sign in to view all comments.