React is a JavaScript library for building user interfaces, particularly single-page applications. It was developed by Facebook (now Meta) and is maintained by both Facebook and a community of individual developers and companies. React allows developers to create large web applications that can change data without reloading the page.
React is not a full-fledged framework like Angular or Vue. It’s focused specifically on the view layer of an application, making it more flexible but requiring additional libraries for full application development.
The easiest way to start a new React project is using Create React App, a tool that sets up a modern React application with a good default configuration:
Copy
# Using npx (recommended)npx create-react-app my-react-app# Or using Vite for a faster, more modern setupnpm create vite@latest my-react-app -- --template react# Navigate to the project directorycd my-react-app# Start the development servernpm start # for Create React App# ornpm run dev # for Vite
Components are the building blocks of React applications. They are reusable pieces of code that return React elements describing what should appear on the screen.
JSX (JavaScript XML) is a syntax extension for JavaScript that looks similar to HTML but allows you to write HTML-like code in your JavaScript files.
Copy
const element = <h1>Hello, world!</h1>;// JSX with expressionsconst name = 'John';const greeting = <h1>Hello, {name}!</h1>;// JSX with attributesconst link = <a href="https://reactjs.org" className="link">React Website</a>;// JSX with childrenconst container = ( <div> <h1>Title</h1> <p>Paragraph</p> </div>);
JSX is transformed into regular JavaScript function calls by tools like Babel:
Copy
// This JSXconst element = <h1 className="greeting">Hello, world!</h1>;// Gets transformed into this JavaScriptconst element = React.createElement( 'h1', { className: 'greeting' }, 'Hello, world!');
React components have a lifecycle - they are created (mounted), updated, and destroyed (unmounted). You can hook into these phases to run code at specific times.
import React, { useState, useEffect } from 'react';function UserProfile({ userId }) { const [user, setUser] = useState(null); const [loading, setLoading] = useState(true); // Similar to componentDidMount and componentDidUpdate useEffect(() => { // This function runs after the component mounts and when userId changes setLoading(true); fetch(`https://api.example.com/users/${userId}`) .then(response => response.json()) .then(data => { setUser(data); setLoading(false); }); // Cleanup function (similar to componentWillUnmount) return () => { // Clean up any subscriptions or timers here console.log('Component is unmounting or userId is changing'); }; }, [userId]); // Only re-run if userId changes if (loading) return <div>Loading...</div>; if (!user) return <div>User not found</div>; return ( <div> <h2>{user.name}</h2> <p>Email: {user.email}</p> </div> );}
import React, { useState, useMemo, useCallback } from 'react';function ExpensiveCalculation({ a, b }) { // useMemo memoizes the result of a computation const result = useMemo(() => { console.log('Computing result...'); // Simulate expensive calculation return a * b; }, [a, b]); // Only recompute if a or b changes // useCallback memoizes a function const handleClick = useCallback(() => { console.log(`Result is ${result}`); }, [result]); // Only recreate if result changes return ( <div> <p>Result: {result}</p> <button onClick={handleClick}>Log Result</button> </div> );}