Learning React as a Frontend Developer with 3.5 Years of Vue Experience
React.js

Learning React as a Frontend Developer with 3.5 Years of Vue Experience

I have spent three and a half years working as a frontend developer, primarily using Vue.js. Recently, for personal reasons, I took a career break, which provided the perfect opportunity to dive into learning React. This learning journey has been incredibly beneficial for my personal well-being.

Since teaching is one of the best ways to learn, I basically write all my articles to improve my learning quality. By sharing my learning process and articulating my newfound knowledge, I can deepen my understanding. I also appreciate feedback and corrections to help me grow and ensure the accuracy of my insights.

Nonetheless, if any part of these articles can inspire or support others who hesitate to make changes in their lives, I would be delighted. I needed support and courage to start this transition, and I am grateful to those who encouraged me. People sometimes think that switching frameworks or languages is a daunting task but it shouldn’t be. Because as developers, our core skill is the ability to learn. Modern frameworks share similar goals and concepts; while their syntax and approaches may differ, these differences can enhance our understanding of fundamental development principles.

As Marie Curie said, “Nothing in life is to be feared, it is only to be understood. Now is the time to understand more so that we may fear less.”

The first part of this article series will serve as a warm-up. I’ll start with a prologue about React and JSX, setting the stage for the more technical details that will follow in the second part.

Who Is This Series For and What Will It Cover?

This article series is not intended for complete beginners. It will not provide detailed explanations of core JavaScript, HTML, or CSS concepts. Instead, it aims to teach specific React concepts, offer insights on when and how to use them, and include code examples for better understanding. As someone experienced in Vue, I will also make comparisons to highlight similarities and differences.

Since this is not a beginner-level series, I will not cover topics from beginner to advanced in a linear fashion. Instead, I will handle concepts and start with the basics but also build them up to a more advanced level.

The method will be as follows:

  1. Explanation of the concept
  2. Why and when to use it
  3. How to use it
  4. A simple code example
  5. Comparisons or annotations if necessary

What Topics Will This Series Cover?

The topics and plan for this series may evolve during the writing and publishing process, but the current planned topics are:

1-) Understanding React: Is It a Library or a Framework?

  • Comparisons with Other Frameworks ( like Angular or Vue )

2-) What is JSX Anyway?

3-) How Does React Render JSX to the DOM?

4-) General Structure for Class and Functional Components and Their Lifecycle

  • Class Components and Lifecycle Methods
  • Functional Components and Hooks

5-) Managing State, Props, and Data Flow in React

  • Handling State in Class Components (state, setState) and Functional Components (useState hook)
  • One-Way Data Flow, Lifting State Up, and Passing Props to Child Components
  • Event Handling and Passing Functions as Props
  • Using the useReducer Hook for Complex State Structures

6-) Prop Drilling and Advanced State and Props Management Ways in React

  • Context API
  • Redux and Redux-thunk
  • Side Effects and useEffect Hook
  • Memoization with useMemo

7-) Conditional Rendering and Displaying Lists on React

  • Conditional Rendering Techniques
  • Rendering Lists with the map Method

8-) How Do Re-Rendering and the Virtual DOM Work?

  • When Components Re-render
  • Preventing Unwanted Re-Rendering mechanisms on React: shouldComponentUpdate, React.memo, and the useCallback Hook

9-) Preventing Code Duplication in React and Differences Between Approaches

  • Custom Hooks
  • Higher-Order Components (HOCs)
  • Render Props
  • Renderless Components
  • Utilities

10-) Folder Structure Approaches

11-) Basic Routing

  • Introduction to React Router, Setting Up Routes, and Dynamic Routing
  • Handling Nested Routes and Route Parameters

12-) Suspense and Lazy Loading

  • Using Suspense and React.lazy for Code Splitting and Performance

13-) Portals

  • Rendering Components Outside the DOM Hierarchy with Portals

14-) Error Boundaries

  • Handling Errors in React with Error Boundaries

Now, enough with the preliminaries. Let’s dive into some real action.

1-) Understanding React: Is It a Library or a Framework?

Ever wondered if React is a library or a framework? You’re not alone. According to the official documentation, “React is a JavaScript library for building user interfaces.” This definition is straightforward, but if you’re used to working with JS frameworks, the term “library” might be confusing. It certainly was for me, and I’ve seen many discussions about it. Some might think, “Library or framework, what’s the difference? It just does what it does, so just use it.” But for those of us who love to split hairs, we need to satisfy that curiosity. So, let’s dive into it together.

Definitions: Library vs. Framework

To understand why React is a library and not a framework, we need to grasp the differences between the two:

  • Library: A collection of pre-written code that users can call upon to solve common problems or add functionality to their applications. Libraries typically focus on specific points, letting developers handle other aspects themselves.
  • Framework: A comprehensive platform providing a structured and standardized way to build and deploy applications.

Comparing React with Vue

As developers using frameworks like Vue (as I do), Angular, Svelte, or Ember, you might think, “But React handles structure with routing, state management, component conventions, hooks, and even server components.” You’re right; many packages used to create React projects offer these functionalities. However, most of them are not made by the React core team; they are made by the React community. You can code using just React without them.

As a Vue developer, this confused me at first because we can do the same with Vue. We can import the Vue script and use it as a library. However, Vue’s “progressive web framework” definition is spot on. You can use Vue like a library without any push to use its packages. But since the Vue core team, led by Evan You, aims to make things easier, they developed many packages like Vue Router, Vuex, Vue CLI, Vue Loader, Vue Devtools, Vue Server Renderer, and Vue Test Utils, etc…

React’s Core and Community Tools

Official React tools made by the core team include the React Core Library, React DOM, React Native, React DevTools, and React Server Components. Other tools such as React Router, Redux, Create React App, and many hooks are developed by the community.

Summary

  • Vue: Can be seen as a warm-blooded and friendly companion offering help for almost any need in your application development but no pressure to add Vue Router, Vuex, etc… they’re just there if you need ’em — thanks, Evan You!
  • React: Is like a cool friend who minds his own business, focusing on building UIs with performance using JSX syntax. His circle of friends is so big that you can easily find any need you wish with his connections.
  • Angular: Can be likened to a strict mentor with his own ways of doing almost everything, pushing you to follow his best practices and being very precise.

I hope this explanation satisfies you as much as it did me.

2-) What is JSX Anyway?

JSX basically means putting HTML and JS in a box and mixing them as with this powerful dust you can make your magic. If you coded with Vue before a similar structure exists there too. You can write JS code inside on Vue template too but there is a saying like “On Vue, you even code your JS on HTML-like structure, and on React you even write HTML as JS-like”. I strongly agree with that. That’s why JS developers love React this much; if you know some HTML basics the rest is your beloved JS and your JSX cake comes out of the oven.

JSX is highly supported by JS translators like Babel. They take your JSX or modern JS (like ES6+) code and transform it into older versions so every browser can groove with your awesome creations.

Let’s look at a simple JSX example:

import React from 'react';

const Greeting = () => {
  const name = 'Ahmet Otenkaya';
  const greetingMessage = `Hello, ${name}!`;

  return (
    <div>
      <p>Current time: {new Date().toLocaleTimeString()}</p>
      <p>{greetingMessage}<p>
    </div>
  );
};

export default Greeting;        

Here’s our friend Greeting, a functional component — which you’ll learn what is it in the next topic — in all its JSX glory. The magic happens inside those curly braces—where you blend your HTML tags with dynamic JavaScript bits. We’ve got variables (name and greetingMessage) doing their thing, and even a nifty date stamp using plain ol’ JavaScript.

  • Remember, whenever you’re mixing JS inside JSX, keep it snug in {}it’s like a little hug to remind JSX that it’s not just another static HTML tag. Oh, and in Vue, it’s a bit different you should wrap your JS code with double brackets {{ }} cuz I told you Vue is very HTML-like and you should wrap your JS code better to ensure it doesn’t get lost ?? )
  • While you can write most of your JS inside JSX syntax, there are some limitations. For instance, you can’t define variables or functions inside JSX directly; you should define them in your component and then use them inside JSX. Similarly, classical if statements aren't allowed inside JSX, but you can use the ternary operator (condition ? ifTrue : else) or the nullish coalescing operator (leftExpr ?? rightExpr). Additionally, you can't use for or while loops directly inside JSX, but you can utilize built-in Array methods like map, filter, etc.

So there you have it JSX in React is your go-to for crafting UIs that marry the elegance of HTML with the power of JavaScript. Get mixin’ and make your frontend shine!

3-) How Does React Render JSX to the DOM?

To understand how React renders JSX to the DOM, let’s start by creating a React project so you can see the general folder structure yourself. You can also use it as a playground for code examples and every topic you learn, helping you to learn better by not only reading but also coding yourself. We’ll use a frontend building tool named Vite, which offers faster runtime compilation speeds compared to other tools like create-react-app. However, the fundamental process remains the same across different project setups.

Create a React Project with Vite:

1. Create the Project:

npm create vite@latest        

Follow the prompts:

  • Project Name: Choose a name for your project.
  • Framework: Select “React”.
  • Variant: Select “JavaScript”.

2. Navigate and Install Dependencies:

cd your-project-name
npm install
npm run dev        

These commands will navigate into the project folder, install the necessary packages, and start the development server. Tada! Here is your first React project created!

In some project setups, the index.html file might be inside the public folder, and the main file might be named index.jsx instead of main.jsx. These variations are not crucial for our topic.

Rendering JSX to the DOM

Let’s understand how React renders JSX to the DOM with the following files:

<!-- index.html -->

<!doctype html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <link rel="icon" type="image/svg+xml" href="/vite.svg" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Vite + React</title>
  </head>
  <body>
    <div id="root"></div>
    <script type="module" src="/src/main.jsx"></script>
  </body>
</html>        

Our HTML file contains a div with the id root, which serves as the mounting point for your React application. The script tag includes the main.jsx file, which is the entry point of the React application.

// main.jsx

import React from 'react'
import ReactDOM from 'react-dom/client'
import App from './App.jsx'
import './index.css'

ReactDOM.createRoot(document.getElementById('root')).render(
  <React.StrictMode>
    <App />
  </React.StrictMode>,
)        

Since we understand how React takes our main component and where to render its code, it’s this simple. Let’s take a little peek at how the rendering process of React works:

The Rendering Process in Detail

The fundamental principle of rendering JSX to the DOM in React involves transforming JSX into React Elements. These elements are lightweight JavaScript objects that represent the underlying DOM nodes for your application. Here’s how the process unfolds:

1. Creating React Elements:

  • When you write JSX, it gets transformed into JavaScript using tools like Babel. For example, the JSX <h1>Hello, World!</h1> is transformed into React.createElement('h1', null, 'Hello, World!').

2. Building the Virtual DOM:

  • React uses these React Elements to construct a Virtual DOM, which is a lightweight representation of the actual DOM structure.

3. Reconciliation:

  • React compares the Virtual DOM with the previous state of the DOM to determine the most efficient way to update the actual DOM.

4. Updating the DOM:

  • Finally, React updates the actual DOM with only the parts that have changed, optimizing performance by minimizing DOM manipulations.

The reconciliation and updating of the DOM via re-rendering will be especially important topics for us on ongoing advanced topics. We’ll handle the processes and optimizations for those steps that affect the performance of our application.

Comparison with Vue

It’s interesting to note that this process is quite similar to how Vue works. In a Vue project created with Vite, your index.html contains a div with the id app, and the main.js file mounts the Vue App component:

// main.js in a Vue project

import { createApp } from 'vue';
import './style.css';
import App from './App.vue';

createApp(App).mount('#app');


        

Summary

To sum up, React takes your App component, which generally manages rendering and routing, and mounts it to a root div in your HTML. React transforms JSX into React Elements, builds a Virtual DOM, reconciles it with the previous state, and efficiently updates the actual DOM. This process ensures a smooth and performant user interface, similar to other JavaScript frameworks like Vue.

Since we learned what are React and JSX and how they put our code to DOM we came to an end for the first part of the article. In the second part, we’ll continue with our fourth topic: General Structure for Class and Functional Components and Their Lifecycle.

Thank you so much for sparing your time and reading the article till the end. Hope to see you in the next parts ?

Jatin Kr. Kushwaha

Corporate HR - leadership and development

3 个月

I m interested

回复
Hamid Eghbali

AWS Certified | Full-Stack & Cloud Developer | Cloud Architecture & Solutions | UI Design | E-commerce

3 个月

Please check my profile

回复

要查看或添加评论,请登录

社区洞察

其他会员也浏览了