Introduction to Frontend Development
Introduction to Frontend Development
State
State is a built-in React object used to hold data that may change over time.
This data is specific to each component and determines how that component
renders and behaves.
Usage: State is typically used to manage things like user inputs,
dynamic data, and UI elements that change (like dropdowns, modals,
or the value of a counter).
Updating State: State is mutable, meaning it can change over time.
However, it should be updated using functions like setState (in class
components) or useState (in functional components with Hooks) to
trigger a re-render.
Example:
javascript
import React, { useState } from 'react';
function Counter() {
const [count, setCount] = useState(0); // Initialize state wit```h 0
return (
<div>
<p>Count: {count}</p>
<button onClick={() => setCount(count +
1)}>Increase</button>
</div>
);
}
In this Counter component, count is a piece of state. Every time the
button is clicked, the setCount function updates the state, and React
re-renders the component with the new count.
Props (Properties)
Props (short for “properties”) are inputs passed from one component to
another, allowing data to flow from a parent component to its children. Props
make components reusable and customizable.
Immutability: Unlike state, props are immutable; they cannot be
modified within the child component that receives them. Instead, the
parent component controls the props.
Usage: Props are useful for passing dynamic data into components or
customizing them based on where they’re used. For instance, you can
pass different titles or images to multiple ProductCard components.
Example:
javascript
function Greeting({ name }) {
return <h1>Hello, {name}!</h1>;
}
function App() {
return <Greeting name="Alice" />;
}
In this example, the App component passes the name prop with a
value of "Alice" to the Greeting component, which renders “Hello,
Alice!”
Hooks
Hooks are special functions in React that allow you to "hook into" React
features like state and lifecycle methods within functional components. The
two most common hooks are useState (for managing state) and useEffect (for
handling side effects).
● Common Hooks:
o useState: Manages state in functional components, as shown in the
Counter example above.
o useEffect: Manages side effects like data fetching, subscriptions,
or directly interacting with the DOM. It runs code in response to
changes in component props or state.
● Usage: Hooks bring flexibility to functional components, allowing
them to manage state and handle effects without needing class
components. This simplifies component design and improves code
readability.
● Example of useEffect:
javascript
import React, { useState, useEffect } from 'react';
function DataFetcher() {
const [data, setData] = useState([]);
useEffect(() => {
fetch('https://jsonplaceholder.typicode.com/posts')
.then(response => response.json())
.then(data => setData(data));
}, []); // Empty dependency array means it runs once after
initial render
return (
<div>
{data.map(post => (
<p key={post.id}>{post.title}</p>
))}
</div>
);
}
Here, useEffect is used to fetch data from an API once the
component mounts. The empty dependency array ([]) ensures the
effect runs only on the initial render.
Angular
▪ Angular is a comprehensive, enterprise-grade framework
developed by Google, commonly used for large-scale applications.
▪ It includes built-in tools for routing, state management, and form
handling, making it a powerful choice for feature-rich applications.
▪ Core Concepts: MVC architecture, two-way data binding,
TypeScript integration.
(Here’s an explanation of Angular's core concepts—MVC
Architecture, Two-Way Data Binding, and TypeScript Integration
—along with details on how they contribute to Angular’s functionality
and efficiency.)
MVC Architecture (Model-View-Controller)
Angular follows the Model-View-Controller (MVC) architecture, which is a
design pattern for separating concerns in an application, making it more
modular, maintainable, and scalable. In Angular’s case, it uses a variation of
MVC known as MVVM (Model-View-ViewModel) but maintains the core
idea of separating data, presentation, and business logic.
● Model: Represents the data or the business logic of the
application. It doesn’t directly interact with the view but holds all
the data that the application uses. In Angular, the model can be
service classes or data models that interact with the backend API
and fetch or manipulate data.
● View: The View is responsible for displaying data to the user. In
Angular, the view is defined using HTML templates. Angular
templates use directives and data binding to display data
dynamically and respond to user input.
● Controller/ViewModel: In Angular, this role is primarily taken
by components. Components control the data that appears in the
view and respond to user input. Each component manages its own
view and interacts with the model through services.
Example:
typescript
// Model - user.model.ts
export interface User {
id: number;
name: string;
email: string;
}
ngOnInit() {
this.userService.getUsers().subscribe((data) => this.users =
data);
}
}
// View - user.component.html
<div *ngFor="let user of users">
<p>{{ user.name }} ({{ user.email }})</p>
</div>
@Component({
selector: 'app-example',
templateUrl: './example.component.html',
})
export class ExampleComponent {
name: string = '';
}
// View - example.component.html
<input type="text" [(ngModel)]="name" placeholder="Enter
your name" />
<p>Hello, {{ name }}!</p>
In this example, typing into the input box immediately updates the
name variable in the component, and changes to the variable are
immediately reflected in the paragraph below the input field.
TypeScript Integration
Angular is built using TypeScript, a statically-typed superset of JavaScript.
TypeScript allows Angular to provide a strongly typed development
environment, making code more predictable and manageable.
Key Benefits of TypeScript in Angular:
● Static Typing: TypeScript’s static typing helps catch errors at
compile time, preventing many runtime errors that might occur in
JavaScript. This is especially helpful in large applications.
● Enhanced IDE Support: TypeScript provides better
autocompletion, inline documentation, and error-checking in IDEs,
making development faster and more efficient.
● Object-Oriented Features: TypeScript allows for classes,
interfaces, and other object-oriented programming constructs,
making code modular and reusable.
● Compatibility with JavaScript: TypeScript compiles to plain
JavaScript, so any valid JavaScript code is also valid in TypeScript,
providing backward compatibility.
Example:
typescript
// user.model.ts - defining an interface for User data
export interface User {
id: number;
name: string;
email: string;
}
@Injectable({
providedIn: 'root',
})
export class UserService {
private apiUrl = 'https://api.example.com/users';
Vue.js
▪ Vue is a progressive framework known for its simplicity and
flexibility, often chosen for smaller, lightweight applications.
▪ It combines the strengths of Angular and React, offering a simple,
reactive approach to building user interfaces.
▪ Core Concepts: Reactive data binding, components, Vuex for state
management.
Here’s an overview of Vue.js core concepts— Reactive Data
Binding, Components, and Vuex for State Management—with an
explanation of each concept and how they work together to create efficient,
reactive applications.
<script>
export default {
data() {
return {
message: '' // Reactive property
};
}
};
</script>
In this example, v-model binds the message data property to the input. When the
user types into the input, the message value updates instantly, and the paragraph
displaying {{ message }} also updates in real time.
Components
In Vue, components are reusable, self-contained elements that encapsulate
HTML, CSS, and JavaScript. They allow developers to break down complex
UIs into smaller, manageable pieces, making development more modular and
organized.
Key Features of Components in Vue:
● Template: The HTML structure of the component, which defines what
will be rendered.
● Script: The logic and data that the component uses. This includes data,
methods, computed properties, and lifecycle hooks.
● Styles: CSS that styles the component, which can be scoped to prevent
styles from leaking into other components.
Types of Components:
● Single-File Components: Vue’s most popular component format, where
template, script, and styles are all defined in a single .vue file.
● Global Components: Defined once and accessible anywhere in the Vue
instance.
● Local Components: Declared within a single component’s scope and
only accessible within that component.
Example:
html
<!-- ParentComponent.vue -->
<template>
<div>
<ChildComponent :message="parentMessage"
@childEvent="handleEvent" />
</div>
</template>
<script>
import ChildComponent from './ChildComponent.vue';
export default {
components: {
ChildComponent
},
data() {
return {
parentMessage: 'Hello from Parent'
};
},
methods: {
handleEvent(payload) {
console.log('Event received from child:', payload);
}
}
};
</script>
html
<script>
export default {
props: ['message'],
methods: {
emitEvent() {
this.$emit('childEvent', 'Hello Parent!'); // Emit event to
parent
}
}
};
</script>
In this example, ParentComponent passes a message prop to ChildComponent,
while ChildComponent communicates back to the parent by emitting a
childEvent with a payload.
Vue.use(Vuex);
html
<!-- CounterComponent.vue -->
<template>
<div>
<p>Counter: {{ counter }}</p>
<button @click="incrementCounter">Increment</button>
</div>
</template>
<script>
import { mapGetters, mapActions } from 'vuex';
export default {
computed: {
...mapGetters(['counterValue'])
},
methods: {
...mapActions(['incrementCounter'])
}
};
</script>
In this example:
● state.counter holds the value of the counter.
● mutations.increment updates the counter value directly.
● actions.incrementCounter calls the mutation, allowing for future
asynchronous operations if needed.
● The CounterComponent uses mapGetters to access the counterValue and
mapActions to call incrementCounter, demonstrating the centralized data
flow with Vuex.