React Hooks like useState and useEffect, along with the Context API, are fundamental for
advanced state management and side effect handling in functional components.
1. useState Hook:
● useState allows functional components to manage local state.
● It returns a stateful value and a function to update it.
● Example:
import React, { useState } from 'react';
function Counter() {
const [count, setCount] = useState(0); // count is the state, setCount is the
updater
return (
<div>
<p>Count: {count}</p>
<button onClick={() => setCount(count + 1)}>Increment</button>
</div>
);
}
2. useEffect Hook:
● useEffect handles side effects in functional components, such as data fetching,
subscriptions, or manual DOM manipulations.
● It runs after every render by default, but its execution can be controlled using a
dependency array.
● Example:
import React, { useState, useEffect } from 'react';
function DataFetcher() {
const [data, setData] = useState(null);
useEffect(() => {
// This effect runs once after the initial render (empty dependency
array)
fetch('[Link]
.then(response => [Link]())
.then(data => setData(data));
}, []); // Empty dependency array means it runs only once
return (
<div>
{data ? <p>Data: {[Link]}</p> : <p>Loading...</p>}
</div>
);
}
3. Context API:
● The Context API provides a way to pass data through the component tree without
manually passing props down at every level.
● It's useful for sharing global data like themes, user authentication, or language
preferences.
● Components:
o createContext: Creates a Context object.
o Provider: A component that provides the context value to its children.
o Consumer (or useContext hook): A component that subscribes to context
changes and reads the value.
● Example with useContext:
import React, { createContext, useContext, useState } from 'react';
const ThemeContext = createContext(null);
function ThemeProvider({ children }) {
const [theme, setTheme] = useState('light');
return (
<[Link] value={{ theme, setTheme }}>
{children}
</[Link]>
);
}
function ThemeSwitcher() {
const { theme, setTheme } = useContext(ThemeContext);
return (
<button onClick={() => setTheme(theme === 'light' ? 'dark' :
'light')}>
Switch to {theme === 'light' ? 'Dark' : 'Light'} Theme
</button>
);
}
function App() {
return (
<ThemeProvider>
<ThemeSwitcher />
</ThemeProvider>
);
}
UI/UX Libraries:
Complementing these core React features, several UI/UX libraries enhance development
and user experience:
● Component Libraries:
o Material-UI (MUI): A comprehensive set of React components implementing
Google's Material Design.
o Ant Design: A design system and React UI library for enterprise-level
products.
o Chakra UI: A modular and accessible component library for building modern
React applications.
o React Bootstrap: Rebuilds Bootstrap components with React.
● Styling Libraries:
o Styled Components: For writing CSS-in-JS, allowing direct styling within
components.
o Emotion: Another performant and flexible CSS-in-JS library.
o Tailwind CSS: A utility-first CSS framework for rapidly building custom
designs.
● Animation Libraries:
o Framer Motion: A production-ready motion library for React.
o React Spring: A spring-physics based animation library.
Material UI and Bootstrap are popular front-end frameworks that facilitate responsive web
design, ensuring websites adapt to various screen sizes and devices. Both employ similar
core techniques, but with distinct implementations.
Key Responsive Design Techniques:
● Grid System:
o Both frameworks utilize a 12-column responsive grid system. This allows
developers to define how content is laid out and how columns resize or stack
on different screen sizes.
o Bootstrap: Uses classes like col-xs-*, col-sm-*, col-md-*, col-lg-* to define
column widths at specific breakpoints (extra small, small, medium, large
screens).
o Material UI: Provides a Grid component with xs, sm, md, lg, xl props, which
correspond to the same breakpoints for defining column ratios.
● Breakpoints:
o Both frameworks define specific screen widths (breakpoints) at which the
layout and styling of components change.
o Bootstrap: Predefined breakpoints are managed through CSS media queries.
o Material UI: Offers a useMediaQuery hook for React, allowing components to
dynamically adjust based on CSS media queries and breakpoints.
● Containers:
o Containers are used to center and constrain the width of content, providing
consistent spacing and readability across different screen sizes.
o Both frameworks offer container components or classes (.container in
Bootstrap, Container component in Material UI) that adapt their width based
on breakpoints.
● Flexible Components:
o Components from both libraries are designed to be inherently responsive,
adjusting their size, appearance, and behavior based on the available screen
space. This includes navigation bars, cards, forms, and other UI elements.
Differences in Implementation:
● Approach: Bootstrap is more utility-class-based, while Material UI is component-
based and built for React, offering a more integrated experience within a React
application.
● Aesthetics: Material UI adheres to Material Design principles, emphasizing visual
depth, animations, and a distinct aesthetic, while Bootstrap offers a more general-
purpose and customizable design.
● Customization: Material UI offers extensive theming capabilities for deep
customization, while Bootstrap provides variables and mixins for modifying its
default styles.
React Hooks, specifically useState and useEffect, are fundamental tools for
advanced UI development and state management in functional React components.
1. useState for State Management:
● Purpose: useState enables functional components to manage local state,
eliminating the need for class components for this purpose.
● Usage: It returns an array containing the current state value and a function to
update that state.
JavaScript
const [count, setCount] = useState(0);
● count represents the current state value.
● setCount is the function used to update count.
● Updating State: When setCount is called, React re-renders the component,
reflecting the updated state in the UI. For updates based on the previous
state, a callback function can be passed to the setter:
JavaScript
setCount(prevCount => prevCount + 1);
2. useEffect for Side Effects:
● Purpose: useEffect allows functional components to perform side effects,
such as data fetching, subscriptions, or direct DOM manipulation, after
rendering.
● Usage: It takes a function (the "effect") and an optional dependency array.
JavaScript
useEffect(() => {
// Perform side effect here
[Link] = `Count: ${count}`;
// Optional cleanup function
return () => {
// Cleanup code (e.g., unsubscribe from a subscription)
};
}, [count]); // Dependency array
● Dependency Array:
● An empty array ([]) means the effect runs only once after the initial
render (like componentDidMount).
● Omitting the array means the effect runs after every render.
● Including variables in the array means the effect runs whenever those
variables change. This is crucial for preventing unnecessary re-runs
and potential performance issues.
Advanced Considerations:
● Custom Hooks: Encapsulate reusable stateful logic into custom hooks
(functions starting with use) to improve code organization and reusability
across components.
● Performance Optimization: Use useMemo and useCallback in conjunction
with useEffect to memoize expensive computations or prevent
unnecessary re-creation of functions, optimizing performance in complex
components.
● Complex State Logic: For more intricate state management beyond simple
values, useReducer offers a powerful alternative to useState, providing a
more structured way to handle state transitions.