1. What is React?
- React is an open-source JavaScript library developed by Facebook in 2013.
- It is mainly used for building user interfaces, especially single-page applications (SPAs).
- React allows developers to create reusable UI components that efficiently update when data changes.
2. Why Use React?
- Fast and Efficient: Uses a Virtual DOM to update only the changed parts of the UI.
- Component-Based Architecture: Breaks the UI into smaller, reusable pieces.
- Declarative Syntax: Helps create interactive UIs with minimal effort.
- SEO-Friendly: React apps can be optimized for search engines.
3. React Key Features
a) JSX (JavaScript XML)
JSX allows you to write HTML inside JavaScript, making the UI code more readable.
Example:
const element = <h1>Hello, React!</h1>;
ReactDOM.render(element, document.getElementById("root"));
b) Components
Components are independent and reusable building blocks of a React application.
Example of a functional component:
function Welcome() {
return <h2>Welcome to React!</h2>;
}
c) State and Props
- State: Used to manage data inside a component.
- Props: Used to pass data between components.
Example:
function Message(props) {
return <h2>Hello, {props.name}!</h2>;
}
ReactDOM.render(<Message name="Zia" />, document.getElementById("root"));
4. How React Works?
- React creates a Virtual DOM, which is a lightweight copy of the real DOM.
- When data changes, React updates only the necessary parts of the UI.
- This process improves performance and speed.
5. Setting Up a React Project
To start using React, follow these steps:
- Install Node.js and npm (Node Package Manager).
- Create a React app using:
npx create-react-app my-app
cd my-app
npm start
- This will start a development server with a default React setup.
6. First React Component (Hello World)
Create a simple React component and render it to the page:
import React from "react";
import ReactDOM from "react-dom";
function App() {
return <h1>Hello, React!</h1>;
}
ReactDOM.render(<App />, document.getElementById("root"));
7. Conclusion
- React simplifies UI development with reusable components.
- The Virtual DOM enhances performance by minimizing updates.
- React is widely used for modern web development, making it a must-learn technology for developers.