React.js is a powerful and popular JavaScript library used for building user interfaces, mainly single-page applications(SPAs). Created and maintained by Facebook, it enables developer to build fast and scalable applications with re-usable components.
Over the time, React has developed a robust ecosystem that supports various aspects of front-end development including state management, routing, testing and much more.
Key Features of React.js
- Component Based Architecture
- State management
- Component Lifecycle
- React Router
- Hooks
- Context API
- React Ecosystem tools and Libraries
Component-Based Architecture
React is all about building applications as a collection of components. Components can be thought of as reusable pieces of UI that can have their own state and behavior. Components can be functional or class-based, but with the introduction of Hooks, functional components are more common in modern React development.
// Functional Component
function Welcome(props) {
return <h1>Hello, {props.name}</h1>;
}
State Management
State management is a key concept in React. The state is an object that holds dynamic data and controls the behavior of the component. In React, managing the state of your application efficiently is crucial, especially as your app grows in complexity.
Local State Management:
Each component can manage its own local state using the useState
hook:
import React, { useState } from 'react';
function Counter() {
const [count, setCount] = useState(0);
return (
<div>
<p>You clicked {count} times</p>
<button onClick={() => setCount(count + 1)}>Click me</button>
</div>
);
}
Global State Management:
For more complex applications, global state management solutions like Redux, Context API, or third-party libraries like MobX can be used to manage the application's state globally.
Component Lifecycle
React components have a lifecycle, which is divided into three main phases:
- Mounting: The phase when a component is being added to the DOM.
- Updating: When a component is re-rendered due to changes in props or state.
- Unmounting: When a component is removed from the DOM.
With the introduction of Hooks, lifecycle methods in class components have been largely replaced with hooks like useEffect
.
Lifecycle in Class Components:
class MyComponent extends React.Component {
componentDidMount() {
// Called after the component is mounted
}
componentDidUpdate(prevProps, prevState) {
// Called after the component is updated
}
componentWillUnmount() {
// Called before the component is removed from the DOM
}
render() {
return <div>Hello, Lifecycle!</div>;
}
}
Lifecycle with Hooks:
import React, { useEffect } from 'react';
function MyComponent() {
useEffect(() => {
// Equivalent to componentDidMount and componentDidUpdate
return () => {
// Equivalent to componentWillUnmount
};
}, []); // Empty array makes it run only on mount and unmount
return <div>Hello, Lifecycle with Hooks!</div>;
}
React Router
React Router is a powerful routing library built specifically for React applications. It enables navigation between different components (or views) and helps manage the browser’s history.
import { BrowserRouter as Router, Route, Routes, Link } from 'react-router-dom';
function Home() {
return <h2>Home</h2>;
}
function About() {
return <h2>About</h2>;
}
function App() {
return (
<Router>
<nav>
<Link to="/">Home</Link>
<Link to="/about">About</Link>
</nav>
<Routes>
<Route path="/" exact component={Home} />
<Route path="/about" component={About} />
</Routes>
</Router>
);
}
- Route: Defines a path and the component to render.
- Link: Enables navigation between routes.
- Routes: Ensures only one route is rendered at a time.
Hooks
Hooks are functions that let you "hook into" React state and lifecycle features from function components. The most common hooks are useState
and useEffect
.
- useState: Manages the local state.
- useEffect: Manages side effects like data fetching, DOM manipulation, and subscriptions.
import React, { useState, useEffect } from 'react';
function DataFetcher() {
const [data, setData] = useState(null);
useEffect(() => {
fetch('/api/data')
.then((response) => response.json())
.then((data) => setData(data));
}, []);
return <div>{data ? `Fetched Data: ${data}` : 'Loading...'}</div>;
}
Context API
The Context API provides a way to pass data through the component tree without having to pass props manually at every level. It's a great tool for global state management in simple apps.
const ThemeContext = React.createContext('light');
function App() {
return (
<ThemeContext.Provider value="dark">
<Toolbar />
</ThemeContext.Provider>
);
}
function Toolbar() {
return (
<div>
<ThemeButton />
</div>
);
}
function ThemeButton() {
const theme = React.useContext(ThemeContext);
return <button className={theme}>I am styled with {theme} theme</button>;
}
React Ecosystem Tools and Libraries
Redux
Redux is a popular state management library that centralizes the state of your application. It works well with React but adds more complexity.
import { createStore } from 'redux';
import { Provider } from 'react-redux';
const initialState = { count: 0 };
function reducer(state = initialState, action) {
switch (action.type) {
case 'INCREMENT':
return { count: state.count + 1 };
default:
return state;
}
}
const store = createStore(reducer);
function App() {
return (
<Provider store={store}>
<Counter />
</Provider>
);
}
Styled Components
A popular library for styling React components using tagged template literals.
import styled from 'styled-components';
const Button = styled.button`
background: lightblue;
color: white;
padding: 10px;
border-radius: 5px;
`;
function App() {
return <Button>Click Me!</Button>;
}
Next.js
A React framework for building server-rendered applications, offering features like server-side rendering (SSR) and static site generation (SSG).
By mastering these core concepts in React.js, you’ll be well-equipped to build scalable, maintainable applications with modern JavaScript frameworks!