Back
My Developer Journey: From Plain JavaScript to React, TypeScript, and RTK Query
Anish
- September 26, 2024
7 min read
As a seasoned MERN Stack Developer, I embarked on my coding journey with fundamental technologies like Node.js, JavaScript, HTML, and CSS. As projects became more complex, I transitioned to more modern frameworks and libraries like React, TypeScript, and RTK Query. This transition improved both the efficiency of development and the scalability of the applications.
In this blog, I'll share my experiences with moving from plain JavaScript to React and TypeScript, and how I ultimately adopted RTK Query for better state management and API integration.
Why Transition from Plain JavaScript to React: The Benefits of Component-Based Architecture
As my projects grew in complexity, the limitations of plain JavaScript became increasingly evident. Managing UI components, streamlining user interactions, and ensuring the scalability of applications became difficult using vanilla JavaScript To overcome these issues, I transitioned to React, a powerful JavaScript library designed for building modern user interfaces.
Why React Over Plain JavaScript?
React's component-based architecture and virtual DOM improve code organization, scalability, and performance by enabling modular development and efficient UI updates.
Here's how a simple 'Click Me' button behaves differently between plain JavaScript and React:
// JavaScript to update the DOM
const button = document.createElement("button")
button.innerText = "Click Me"
button.addEventListener("click", () => {
document.body.style.backgroundColor = "blue"
})
document.body.appendChild(button)
// React Component
function App() {
const handleClick = () => { document.body.style.backgroundColor = 'blue'; };
return <button onClick={handleClick}>Click Me</button>;
}
Key Benefits of React:
Declarative Syntax:
With React, I could declare what the UI should look like, and React would handle updating the DOM based on state changes.
JSX:
The combination of JavaScript and HTML (JSX) made it easier to write logic and UI in the same place, enhancing readability.
Reusable Components:
React's component-based structure allowed me to create reusable pieces of UI, cutting down on repetitive code and speeding up development.
State Management:
React introduced hooks like useState and useEffect, simplifying state management compared to plain JavaScript. Additionally, hooks like useContext and useMemo further enhanced how state and performance could be optimized in my applications..
In large-scale applications, Redux offered a streamlined global state management solution, significantly reducing code complexity and improving scalability., which eliminated the hassle of passing props through multiple layers of components.
Transitioning from JavaScript to TypeScript: Why Developers Should Make the Switch
One of the most significant shifts in my development process was moving from JavaScript
to TypeScript
. Both JavaScript and TypeScript are widely used in web development. However, TypeScript offers key advantages, particularly in terms of error detection
, type safety, and code scalability
, especially in larger projects.
Example Comparison:
// JavaScript Example
function add(a, b) {
return a + b;
}
add(5, "10"); // Output: "510"
// TypeScript Example
function add(a: number, b: number): number {
return a + b;
}
add(5, "10"); // Error: Argument of type 'string' is not assignable to parameter of type 'number'.
JavaScript
allows for more flexibility, but this can lead to issues when data types don’t match, especially in large applications. TypeScript
, on the other hand, enforces strict typing, making it easier to catch errors early in the development process.
Why Redux Toolkit is the Best State Management Solution for Large React Projects
Once I transitioned to React, managing global state became essential as the application size increased. Redux Toolkit (RTK) simplifies state management by providing a structured way to handle global state with less boilerplate compared to traditional Redux.
Here’s a simplified setup for managing a counter with Redux Toolkit:
// Redux Toolkit Example with TypeScript
import { createSlice } from '@reduxjs/toolkit';
interface CounterState {
value: number;
}
const initialState: CounterState = { value: 0 };
const counterSlice = createSlice({
name: 'counter',
initialState,
reducers: {
increment: (state) => {
state.value += 1;
},
decrement: (state) => {
state.value -= 1;
},
},
});
export const { increment, decrement } = counterSlice.actions;
export default counterSlice.reducer;
Benefits of Using Redux for State Management:
Global State Access:
No more props drilling; components can access state directly from the global store.Predictable State Changes:
Actions and reducers ensure predictable updates, making it easier to manage complex state logic.Scalability:
Redux easily scales with the growing complexity of the application, especially with large amounts of shared state.Improved Debugging:
Redux DevTools provide powerful debugging capabilities to track state changes and dispatched actions.
From Axios to RTK Query: Streamlining API Calls and State Management
In the early stages of my journey, I used Axios for making API requests. While Axios worked well for small-scale applications, handling state, caching, and side effects became increasingly difficult as my projects grew. That’s when I transitioned to RTK Query, an API middleware from Redux Toolkit, which integrates state management and simplifies API handling.
RTK Query Example with TypeScript
// Define the type for API response
interface Post {
id: number;
title: string;
body: string;
}
// RTK Query setup with TypeScript
import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react';
export const api = createApi({
reducerPath: 'api',
baseQuery: fetchBaseQuery({ baseUrl: '/api' }),
endpoints: (builder) => ({
getPosts: builder.query<Post[], void>({
query: () => 'posts',
}),
}),
});
export const { useGetPostsQuery } = api;
RTK Query, when combined with TypeScript, enhances the developer experience by providing:
Type Safety:
Ensures that data is fetched and used correctly without unexpected runtime errors.Automatic Caching:
Caching and refetching are handled out of the box, improving API handling efficiency.Reduced Boilerplate:
Compared to Axios + Redux, RTK Query greatly reduces the boilerplate needed to manage API calls, state, and caching.
Conclusion
Transitioning from plain JavaScript to modern technologies like React, TypeScript, and RTK Query has been a gradual but rewarding process, improving both development speed
and application scalability
. Each step—from adopting React’s component-based architecture to leveraging TypeScript for type safety and utilizing RTK Query for more efficient API management—has drastically improved the scalability and maintainability of my projects.
If you're starting in web app development or looking to scale your applications, adopting these technologies is a worthwhile investment. They may seem daunting at first, but the improvements in developer experience, error prevention, and performance are more than worth the initial learning curve.
FAQ's
1. Why should developers transition from JavaScript to TypeScript?
TypeScript offers static typing, enabling developers to catch errors at compile time, which leads to better error handling and code scalability. This is especially beneficial in large projects, as TypeScript helps prevent bugs and improves developer productivity with better tooling and type inference.
2. What is Redux, and why is it useful in state management?
Redux is a global state management tool that simplifies how data is passed and managed across components. It eliminates "props drilling" and improves scalability, debugging, and performance, especially in large-scale applications where multiple components share the same state.
3. How does RTK Query improve API handling compared to Axios?
RTK Query, integrated with Redux, simplifies API requests by automating caching, state management, and error handling. While Axios requires manual setup for these tasks, RTK Query optimizes API performance and reduces boilerplate code, making it more efficient for handling APIs in large applications.
4. What are the key benefits of using React’s component-based architecture?
React’s component-based structure allows for reusable, self-contained components. This improves code organization, makes applications more modular, and speeds up development by reducing redundant code. It also enhances maintainability and scalability, especially in complex UIs.