
Introduction to React
React is a popular JavaScript library for building user interfaces, particularly for single-page applications where you need a fast and interactive UI. Developed by Facebook, React enables developers to create reusable UI components and manage state efficiently.
React allows developers to build scalable applications by utilizing components, state management, and an efficient virtual DOM. It follows a declarative approach, making the UI more predictable and easier to debug. By leveraging React Hooks, developers can efficiently manage state and lifecycle events without needing class components.
Setting Up a React Project
To get started with React, you need Node.js installed on your system. You can create a new React project using:
npx create-react-app my-app cd my-app npm start
This command sets up a new React application with all the necessary configurations, including Webpack, Babel, and development dependencies.
React Components
React applications are built using components. There are two main types:
- Functional Components (Stateless)
- Class Components (Stateful – rarely used in modern React)
Functional Component Example:
function Greeting() { return <h1>Hello, World!</h1>; } export default Greeting;
Class Component Example:
import React, { Component } from 'react'; class Greeting extends Component { render() { return <h1>Hello, World!</h1>; } } export default Greeting;
In modern React development, functional components are preferred because they are simpler and support hooks for managing state and side effects.
JSX: JavaScript XML
JSX is a syntax extension for JavaScript that allows writing HTML-like code inside JavaScript. JSX makes React code more readable and expressive.
const element = <h1>Welcome to React</h1>;
JSX must be transpiled using Babel before the browser can understand it.
React Hooks
React Hooks allow functional components to have state and other React features. Let’s go through some important hooks.
useState Hook
The useState
hook is used to manage state in functional components.
import React, { useState } from 'react'; function Counter() { const [count, setCount] = useState(0); return ( <div> <p>Count: {count}</p> <button onClick={() => setCount(count + 1)}>Increment</button> </div> ); } export default Counter;
useEffect Hook
The useEffect
hook allows performing side effects in function components.
import React, { useState, useEffect } from 'react'; function Timer() { const [seconds, setSeconds] = useState(0); useEffect(() => { const interval = setInterval(() => { setSeconds(prevSeconds => prevSeconds + 1); }, 1000); return () => clearInterval(interval); }, []); return <p>Timer: {seconds}s</p>; } export default Timer;
useContext Hook
The useContext
hook provides a way to share values like themes and authentication status between components.
import React, { useContext, createContext } from 'react'; const ThemeContext = createContext('light'); function ThemedComponent() { const theme = useContext(ThemeContext); return <p>Current Theme: {theme}</p>; } function App() { return ( <ThemeContext.Provider value="dark"> <ThemedComponent /> </ThemeContext.Provider> ); } export default App;
useRef Hook
The useRef
hook is used to reference DOM elements directly.
import React, { useRef } from 'react'; function FocusInput() { const inputRef = useRef(); const focusInput = () => { inputRef.current.focus(); }; return ( <div> <input ref={inputRef} type="text" /> <button onClick={focusInput}>Focus Input</button> </div> ); } export default FocusInput;
useMemo Hook
The useMemo
hook optimizes performance by memoizing expensive calculations.
import React, { useState, useMemo } from 'react'; function ExpensiveCalculation({ num }) { const result = useMemo(() => { console.log('Calculating...'); return num * 2; }, [num]); return <p>Result: {result}</p>; } function App() { const [num, setNum] = useState(0); return ( <div> <button onClick={() => setNum(num + 1)}>Increase</button> <ExpensiveCalculation num={num} /> </div> ); } export default App;
React Router v6
React Router is used for handling navigation in React applications. To install it, run:
npm install react-router-dom
Basic Setup
import { BrowserRouter as Router, Routes, Route, Link } from 'react-router-dom'; function Home() { return <h1>Home Page</h1>; } function About() { return <h1>About Page</h1>; } function App() { return ( <Router> <nav> <Link to="/">Home</Link> <Link to="/about">About</Link> </nav> <Routes> <Route path="/" element={<Home />} /> <Route path="/about" element={<About />} /> </Routes> </Router> ); } export default App;
useLocation Hook
The useLocation
hook returns the current location object.
import { useLocation } from 'react-router-dom'; function ShowLocation() { const location = useLocation(); return <p>Current Path: {location.pathname}</p>; } export default ShowLocation;
useParams Hook
The useParams
hook retrieves URL parameters.
import { useParams } from 'react-router-dom'; function UserProfile() { const { id } = useParams(); return <h1>User ID: {id}</h1>; }
Passing State via Link
import { Link, useLocation } from 'react-router-dom'; function Home() { return <Link to="/details" state={{ name: 'John Doe' }}>Go to Details</Link>; } function Details() { const location = useLocation(); return <h1>{location.state?.name || 'No Data'}</h1>; }
React is a powerful library that enables developers to build interactive and efficient web applications. By mastering React Hooks and React Router, you can create scalable, maintainable applications with ease.