Transitioning from Angular to React: A guide to master the framework
Mahima Chugh
SDE 2 @ American Express Global Business Travel | Developing Scalable Solutions | FullStack | Java | Python | Angular
This article is a reference for developers who have experience working with Angular and want to expand their learning horizon to React. Learning the framework can feel familiar on various grounds although both the frameworks approach problems differently.
Here are some similarities and differences that you can keep in mind to quickly get up to speed with React:
1. React is a library and Angular is a framework
React solely focuses on building user interfaces and provides tools to render components. It doesn't handle any other aspects of the application like state management, routing or form validations. You need to make use of other libraries such as Redux for state management, React Router for navigation to get a flexible architecture in your project.
Angular is a complete framework and provides us all the tools required to build a full-fledged application, such as tools for routing, form validation, state management, HTTP requests and testing. All these features make it more structured in comparison to Angular.
The simplicity in structure makes React much more friendly for a smaller application. Angular, on the other hand has an enterprise architecture, and comes with a lot more boilerplate code. The structure makes it easier for larger teams to maintain consistency across the project.
React focuses on the "View" part of MVVC(Model-View-ViewModel) architecture, leaving other concerns to external tools. Angular on the other hand, provides an end-to-end solution with built-in tools for every aspect of application development.
2. Component Architecture
Both Angular and React are component driven but React components are simpler and focus primarily on UI.
Angular components are defined with @Component and rely on modules.
@Component({
selector: 'app-example',
templateUrl: './example.component.html',
})
export class ExampleComponent {
title: string = 'Hello Angular';
}
React components use JavaScript classes with JSX for templating.
function ExampleComponent() {
const title = 'Hello React';
return <h1>{title}</h1>;
}
3. State Management
Angular makes use of services or libraries like NgRx for state management. React uses built-in state hooks and libraries like Redux.
Angular:
@Injectable({ providedIn: 'root' })
export class StateService {
private state = new BehaviorSubject<string>('initial state');
state$ = this.state.asObservable();
}
React:
import { useState } from 'react';
function App() {
const [state, setState] = useState('initial state');
return <button onClick={() => setState('new state')}>{state}</button>;
}
4. Routing
Angular uses a powerful router with guards and resolvers while React uses a lighter library, React Router for client side navigation.
Angular:
const routes: Routes = [
{ path: 'home', component: HomeComponent },
{ path: 'about', component: AboutComponent },
];
React:
import { BrowserRouter as Router, Route, Routes } from 'react-router-dom';
function App() {
return (
<Router>
<Routes>
<Route path="/home" element={<Home />} />
<Route path="/about" element={<About />} />
</Routes>
</Router>
);
}
5. Dependency Injection
Angular has a robust system for managing dependencies. Services and decorators such as @Inbjectable help achieve this.
Angular:
@Injectable()
class HeroService {}
@Component({
standalone: true,
selector: 'hero-list',
template: '...',
providers: [HeroService]
})
class HeroListComponent {}
React on the other hand, relies on hooks, such as useContext to share data between components.
function App() {
return (
<ExampleContext.Provider value="example">
<Child />
</ExampleContext.Provider>
);
}
function Child() {
const value = useContext(ExampleContext);
return <p>{value}</p>;
}
6. Data Binding
While Angular offers two-way data binding, React relies on one-way data flow and requires manual updates for two-way binding.
领英推荐
Angular:
Interpolation (One-way: Component → Template)
Binds data from the component to the HTML template.
// component.ts
export class AppComponent {
title = 'Hello, Angular!';
}
// template.html
<h1>{{ title }}</h1> <!-- Displays: Hello, Angular! -->
Property Binding (One-way: Component → Template)
Binds a property in the component to a DOM property.
<img [src]="imageUrl" />
imageUrl = 'https://example.com/image.png';
Event Binding (One-way: Template → Component)
Sends DOM events to the component.
<button (click)="handleClick()">Click me</button>
handleClick() {
alert('Button clicked!');
}
Two-Way Binding (Component ? Template)
Synchronizes data in both directions using [(ngModel)].
<input [(ngModel)]="username" />
<p>Hello, {{ username }}!</p>
username = '';
Note: Two-way binding requires importing the FormsModule:
import { FormsModule } from '@angular/forms';
It comes with one way data binding traditionally where data is transmitted from parent to child. To achieve two-way binding, we need to manage the state using 'useState'.
One-way Data Binding (Parent → Child)
import React from 'react';
const App = () => {
const title = 'Hello, React!';
return <h1>{title}</h1>;
};
export default App;
Event Handling (Child → Parent)
import React, { useState } from 'react';
const App = () => {
const [message, setMessage] = useState('');
const handleChange = (e) => {
setMessage(e.target.value);
};
return (
<div>
<input type="text" value={message} onChange={handleChange} />
<p>Hello, {message}!</p>
</div>
);
};
export default App;
Two-way Binding Simulation
React achieves two-way binding by explicitly updating the state:
import React, { useState } from 'react';
const App = () => {
const [username, setUsername] = useState('');
return (
<div>
<input
type="text"
value={username}
onChange={(e) => setUsername(e.target.value)}
/>
<p>Hello, {username}!</p>
</div>
);
};
export default App;
7. Flexibility:
Angular:
Opinionated and prescriptive, provides a structured way to build applications. Comes with built-in features like forms, HTTP Client, and RxJS.
React:
Highly flexible and un-opinionated. Developers can choose third-party libraries for routing, state management, like, Redux and more.
Conclusion:
We can select any of the framework depending upon the use case. We can choose Angular if we need a comprehensive, ready-to-use framework for large applications. We can choose React if we want to develop dynamic, interactive UIs and prefer a lightweight and modular approach.
Senior Manager, Software Development Engineering @ Egencia, an Amex GBT Company | We are hiring for multiple positions
2 个月Insightful, keep sharing
Head of Engineering - Supply & Booking Capabilities
2 个月Love this! Keep reading, learning and sharing!!!