Modern Web and Mobile Development with React
Introduction to React
What is React?
React is a popular JavaScript library used for building user interfaces. Think of it as a toolkit for creating the visual parts of a website or web application, the parts you actually see and interact with. It was created by Facebook and is now used by countless companies, from startups to giants like Netflix and Airbnb.
React is a JavaScript library for building user interfaces.
The core idea behind React is to break down complex user interfaces into smaller, reusable pieces. Instead of building one massive, tangled page, you build individual, self-contained blocks and then assemble them to create the final product. This approach makes your code cleaner, easier to manage, and more scalable as your application grows.
The Building Blocks: Components
In React, these reusable pieces are called components. A component is like a LEGO brick for your user interface. You can have a component for a button, a search bar, a user profile, or an entire navigation menu. Each component manages its own logic and appearance.
Components are the fundamental building blocks of any React application.
At its simplest, a React component is just a JavaScript function that returns a description of what the UI should look like. This description looks a lot like HTML.
function WelcomeMessage() {
return <h1>Hello, world!</h1>;
}
// You can then use this component elsewhere
// like it's a regular HTML tag:
// <WelcomeMessage />
Writing UI with JSX
Wait, is that HTML inside a JavaScript function? Not exactly. This syntax is called JSX, which stands for JavaScript XML. It's an extension to JavaScript that allows you to write HTML-like code directly in your JavaScript files. It makes writing UI components intuitive because the code for the structure and the logic can live together.
const user = {
name: 'Jane Doe',
avatarUrl: 'https://example.com/avatar.jpg'
};
const userProfile = (
<div>
<h2>{user.name}</h2>
<img
className="avatar"
src={user.avatarUrl}
alt={'Photo of ' + user.name}
/>
</div>
);
Notice two things. First, you can embed JavaScript expressions (like user.name) directly inside your JSX by wrapping them in curly braces {}. Second, since JSX is closer to JavaScript than HTML, some HTML attributes have slightly different names. For example, the HTML class attribute becomes className in JSX to avoid conflicting with the class keyword in JavaScript.
Your browser doesn't understand JSX directly. A tool called a compiler (like Babel) transforms your JSX into regular JavaScript code that browsers can execute.
Managing Data
Components are dynamic. They need to handle data that can change. React gives us two ways to manage data in components: props and state.
Props
noun
Short for "properties," props are used to pass data from a parent component down to a child component. They are read-only, meaning a component cannot change the props it receives.
Think of props as arguments you pass to a function. If our WelcomeMessage component was more flexible, we could pass it a name to greet.
// Child component receives `name` as a prop
function WelcomeMessage(props) {
return <h1>Hello, {props.name}!</h1>;
}
// Parent component
function App() {
return (
<div>
{/* Pass data via props */}
<WelcomeMessage name="Alice" />
<WelcomeMessage name="Bob" />
</div>
);
}
State
noun
State is data that is managed within a component. It's private to that component and can change over time in response to user actions or network responses. When a component's state changes, React automatically re-renders the component to reflect the new data.
To add state to a functional component, you use a special function called the useState Hook. Let's build a simple counter.
import { useState } from 'react';
function Counter() {
// `useState(0)` initializes `count` to 0.
// `setCount` is the function to update it.
const [count, setCount] = useState(0);
return (
<div>
<p>You clicked {count} times</p>
<button onClick={() => setCount(count + 1)}>
Click me
</button>
</div>
);
}
Every time you click the button, setCount is called. This updates the count state variable, and React efficiently re-draws the component on the screen to show the new count.
The Virtual DOM
One of React's key features is the Virtual DOM. Updating the actual browser DOM (the tree-like structure of your webpage) is slow and can be a performance bottleneck. React solves this with a clever abstraction.
When a component's state changes, React doesn't immediately touch the real DOM. Instead, it creates a new in-memory representation of the UI, called the Virtual DOM. It then compares this new virtual tree with the previous one, a process called "diffing."
After calculating the differences, React figures out the most efficient way to make the minimal necessary changes to the real DOM to match the new state. This batching of updates makes React applications feel fast and responsive.
Setting Up Your First App
The easiest way to start a new React project is with a tool called Create React App. It sets up a complete development environment for you with a single command. You don't need to configure anything to get started.
First, you need to have Node.js installed on your computer, which includes npm (Node Package Manager). Once that's ready, open your terminal and run this command:
npx create-react-app my-first-react-app
This command creates a new directory called my-first-react-app with all the necessary files and configurations. To run your new app, navigate into the directory and start the development server:
cd my-first-react-app
npm start
A new browser window will open with your first React application running. You can now open the project files in a code editor, find the src/App.js file, and start experimenting by changing the code. The browser will automatically reload with your changes.
What is the primary purpose of the React library?
What is JSX?
These are the fundamental concepts of React. By understanding components, JSX, props, state, and the Virtual DOM, you have the foundation needed to build powerful and interactive user interfaces.