React has revolutionized how we build user interfaces. Its component-driven architecture, efficient state management, and powerful hooks make it a must-learn library for every frontend developer. In this post, we'll dive into React basics, covering components, props, state, hooks, routing, and more.
Components: The Building Blocks
React applications are built using components. These are reusable, self-contained units of the UI.
Functional Components
Functional components are simple JavaScript functions that return JSX.
Example:
const Greeting = () => {
return <h1>Hello, World!</h1>;
};
Class Components
Class components use ES6 classes and include more complex functionality like lifecycle methods.
Example:
class Greeting extends React.Component {
render() {
return <h1>Hello, World!</h1>;
}
}
Props and State
Props
Props (short for properties) are used to pass data from a parent component to a child component.
Example:
const Welcome = (props) => {
return <h1>Welcome, {props.name}!</h1>;
};
<Welcome name="Shivam" />; // Output: Welcome, Shivam!
State
State is used to manage data that changes over time within a component.
Example:
import React, { useState } from 'react';
const Counter = () => {
const [count, setCount] = useState(0);
return (
<div>
<p>Count: {count}</p>
<button onClick={() => setCount(count + 1)}>Increment</button>
</div>
);
};
React Hooks
Hooks enable functional components to manage state and side effects.
useState
Manages state in functional components.
Example:
const [state, setState] = useState(initialValue);
useEffect
Performs side effects like data fetching, subscriptions, or DOM updates.
Example:
useEffect(() => {
console.log('Component mounted');
return () => console.log('Component unmounted');
}, []); // Empty array means this runs once
useContext
Provides a way to pass data through the component tree without prop drilling.
Example:
const ThemeContext = React.createContext('light');
const App = () => {
return (
<ThemeContext.Provider value="dark">
<Toolbar />
</ThemeContext.Provider>
);
};
const Toolbar = () => {
const theme = useContext(ThemeContext);
return <p>Theme: {theme}</p>;
};
React Router
React Router enables navigation between different pages in a React app.
Example:
import { BrowserRouter as Router, Route, Switch } from 'react-router-dom';
const App = () => {
return (
<Router>
<Switch>
<Route path="/home" component={Home} />
<Route path="/about" component={About} />
</Switch>
</Router>
);
};
Context API and State Management
The Context API is a lightweight solution for managing state globally without third-party libraries like Redux.
Example:
const UserContext = React.createContext();
const App = () => {
const user = { name: "Shivam" };
return (
<UserContext.Provider value={user}>
<Profile />
</UserContext.Provider>
);
};
const Profile = () => {
const user = useContext(UserContext);
return <p>User: {user.name}</p>;
};
Error Boundaries
Error boundaries catch JavaScript errors in the component tree and display fallback UI.
Example:
class ErrorBoundary extends React.Component {
constructor(props) {
super(props);
this.state = { hasError: false };
}
static getDerivedStateFromError(error) {
return { hasError: true };
}
componentDidCatch(error, info) {
console.error(error, info);
}
render() {
if (this.state.hasError) {
return <h1>Something went wrong.</h1>;
}
return this.props.children;
}
}
JSX Syntax
JSX allows you to write HTML-like syntax directly in JavaScript.
Example:
const App = () => {
return (
<div>
<h1>Hello, React!</h1>
<p>JSX is awesome.</p>
</div>
);
};
Conclusion
React's component-based approach, state management capabilities, and robust ecosystem make it an essential tool for modern front-end development. Understanding these basics lays the foundation for building scalable and interactive applications.
In the next post, we’ll explore advanced React concepts, including higher-order components, custom hooks, and performance optimization techniques.
Stay tuned for "Frontend Unlocked: React Advanced!"