JavaScript and React course ยท Module 8: Advanced React Patterns
Design patterns and logic reusability
In this lesson5
On our cosmic journey through the world of React, efficient use of resources is key to mission success. Just as space engineers use proven designs for different spaceship modules, we too can leverage design patterns in React to maximize code reusability and create more scalable applications.
Rendering and composition patterns
1. Higher-Order Components (HOC)
Higher-Order Components (HOC) are functions that take a component and return a new, enhanced component. This is a pattern based on the principle of composition, not inheritance.
// Simple HOC adding time tracking functionality
function withTimer(WrappedComponent) {
return function WithTimer(props) {
const [startTime] = useState(Date.now());
const [currentTime, setCurrentTime] = useState(Date.now());
useEffect(() => {
const timer = setInterval(() => {
setCurrentTime(Date.now());
}, 1000);
return () => clearInterval(timer);
}, []);
const elapsedTime = (currentTime - startTime) / 1000;
return (
<WrappedComponent
{...props}
elapsedTime={elapsedTime}
/>
);
};
}
// Using the HOC
function MissionControl({ missionName, elapsedTime }) {
return (
<div className="mission-control">
<h2>Mission: {missionName}</h2>
<p>Duration: {elapsedTime.toFixed(0)} seconds</p>
{/* rest of component */}
</div>
);
}
const MissionControlWithTimer = withTimer(MissionControl);
// Rendering the enhanced component
function App() {
return <MissionControlWithTimer missionName="Apollo" />;
}2. Render Props
Render Props is a pattern where a component receives a function that tells it what to render. This allows logic to be shared between components.
function MouseTracker({ render }) {
const [position, setPosition] = useState({ x: 0, y: 0 });
useEffect(() => {
function handleMouseMove(event) {
setPosition({
x: event.clientX,
y: event.clientY
});
}
window.addEventListener('mousemove', handleMouseMove);
return () => {
window.removeEventListener('mousemove', handleMouseMove);
};
}, []);
return render(position);
}
// Using render props
function App() {
return (
<MouseTracker
render={({ x, y }) => (
<div className="space-map">
<h2>Star Map</h2>
<p>Cursor coordinates: ({x}, {y})</p>
<div
className="space-ship"
style={{
position: 'absolute',
left: x,
top: y
}}
>
โฒ
</div>
</div>
)}
/>
);
}3. Compound Components Pattern
This pattern allows you to create components that work together while maintaining flexibility and code readability.
function Spaceship({ children }) {
const [power, setPower] = useState(0);
const [shields, setShields] = useState(false);
const contextValue = {
power,
setPower,
shields,
setShields
};
return (
<SpaceshipContext.Provider value={contextValue}>
<div className="spaceship">
{children}
</div>
</SpaceshipContext.Provider>
);
}
// Child components
Spaceship.Engine = function Engine() {
const { power, setPower } = useContext(SpaceshipContext);
return (
<div className="engine">
<h3>Engine</h3>
<p>Power: {power}%</p>
<input
type="range"
min="0"
max="100"
value={power}
onChange={e => setPower(Number(e.target.value))}
/>
</div>
);
};
Spaceship.Shields = function Shields() {
const { shields, setShields } = useContext(SpaceshipContext);
return (
<div className="shields">
<h3>Shields</h3>
<button onClick={() => setShields(!shields)}>
{shields ? 'Deactivate' : 'Activate'} shields
</button>
<p>Status: {shields ? 'Active' : 'Inactive'}</p>
</div>
);
};
// Usage
function App() {
return (
<Spaceship>
<h2>Spaceship Control Panel</h2>
<Spaceship.Engine />
<Spaceship.Shields />
</Spaceship>
);
}State management patterns
1. Flux / Redux
Redux implements the Flux pattern, which assumes a unidirectional data flow. The application state is stored in a single object (store), and state modifications can only occur by dispatching actions that are processed by reducers.
// Actions
const ADD_CREWMEMBER = 'ADD_CREWMEMBER';
const REMOVE_CREWMEMBER = 'REMOVE_CREWMEMBER';
// Action creators
function addCrewmember(member) {
return {
type: ADD_CREWMEMBER,
payload: member
};
}
function removeCrewmember(id) {
return {
type: REMOVE_CREWMEMBER,
payload: id
};
}
// Reducer
function crewReducer(state = [], action) {
switch (action.type) {
case ADD_CREWMEMBER:
return [...state, action.payload];
case REMOVE_CREWMEMBER:
return state.filter(member => member.id !== action.payload);
default:
return state;
}
}
// In a component with react-redux
function CrewManagement() {
const crew = useSelector(state => state.crew);
const dispatch = useDispatch();
function handleAddCrewmember() {
const newMember = {
id: Date.now(),
name: 'New crew member',
role: 'Cadet'
};
dispatch(addCrewmember(newMember));
}
return (
<div>
<h2>Crew Management</h2>
<button onClick={handleAddCrewmember}>Add crew member</button>
<ul>
{crew.map(member => (
<li key={member.id}>
{member.name} - {member.role}
<button onClick={() => dispatch(removeCrewmember(member.id))}>
Remove
</button>
</li>
))}
</ul>
</div>
);
}2. Context API
Context API allows passing data through the component tree without the need to pass props at every level.
// Creating context
const MissionContext = createContext();
// Provider
function MissionProvider({ children }) {
const [mission, setMission] = useState({
name: 'Apollo 11',
status: 'In progress',
crewMembers: [
{ id: 1, name: 'Neil Armstrong', role: 'Commander' },
{ id: 2, name: 'Buzz Aldrin', role: 'Lunar Module Pilot' },
{ id: 3, name: 'Michael Collins', role: 'Command Module Pilot' }
]
});
function updateMissionStatus(newStatus) {
setMission(prev => ({ ...prev, status: newStatus }));
}
function addCrewMember(member) {
setMission(prev => ({
...prev,
crewMembers: [...prev.crewMembers, member]
}));
}
const value = {
mission,
updateMissionStatus,
addCrewMember
};
return (
<MissionContext.Provider value={value}>
{children}
</MissionContext.Provider>
);
}
// Custom hook for easier usage
function useMission() {
const context = useContext(MissionContext);
if (!context) {
throw new Error('useMission must be used within a MissionProvider');
}
return context;
}
// Usage in components
function MissionDashboard() {
const { mission } = useMission();
return (
<div>
<h1>Mission: {mission.name}</h1>
<p>Status: {mission.status}</p>
</div>
);
}
function MissionControl() {
const { updateMissionStatus } = useMission();
return (
<div>
<h2>Mission Control Center</h2>
<button onClick={() => updateMissionStatus('Completed successfully')}>
Complete mission
</button>
<button onClick={() => updateMissionStatus('Aborted')}>
Abort mission
</button>
</div>
);
}
function CrewList() {
const { mission, addCrewMember } = useMission();
return (
<div>
<h2>Mission Crew</h2>
<ul>
{mission.crewMembers.map(member => (
<li key={member.id}>
{member.name} - {member.role}
</li>
))}
</ul>
<button
onClick={() =>
addCrewMember({
id: Date.now(),
name: 'New astronaut',
role: 'Mission Specialist'
})
}
>
Add crew member
</button>
</div>
);
}
// Putting it all together
function App() {
return (
<MissionProvider>
<div className="mission-app">
<MissionDashboard />
<MissionControl />
<CrewList />
</div>
</MissionProvider>
);
}3. Custom hooks for state
As we saw in the previous module, custom hooks are a powerful tool for encapsulating and reusing state-related logic.
function useSpaceshipSystems() {
const [engines, setEngines] = useState({
mainEngine: { power: 0, status: 'offline' },
leftThruster: { power: 0, status: 'offline' },
rightThruster: { power: 0, status: 'offline' }
});
const [lifeSupportSystem, setLifeSupportSystem] = useState({
oxygen: 100,
temperature: 21,
pressure: 1
});
function startEngine(engineName) {
setEngines(prev => ({
...prev,
[engineName]: {
...prev[engineName],
status: 'online',
power: 10
}
}));
}
function setEnginePower(engineName, power) {
if (engines[engineName].status === 'offline') {
console.warn(`Cannot set power - engine ${engineName} is offline`);
return;
}
setEngines(prev => ({
...prev,
[engineName]: {
...prev[engineName],
power: Math.max(0, Math.min(100, power))
}
}));
}
function stopEngine(engineName) {
setEngines(prev => ({
...prev,
[engineName]: {
...prev[engineName],
status: 'offline',
power: 0
}
}));
}
function adjustLifeSupport({ oxygen, temperature, pressure }) {
setLifeSupportSystem(prev => ({
...prev,
...(oxygen !== undefined ? { oxygen } : {}),
...(temperature !== undefined ? { temperature } : {}),
...(pressure !== undefined ? { pressure } : {})
}));
}
return {
engines,
lifeSupportSystem,
startEngine,
setEnginePower,
stopEngine,
adjustLifeSupport
};
}
// Usage
function SpaceshipControls() {
const {
engines,
lifeSupportSystem,
startEngine,
setEnginePower,
stopEngine,
adjustLifeSupport
} = useSpaceshipSystems();
return (
<div className="spaceship-controls">
<h2>Ship Systems Control</h2>
<div className="engines-section">
<h3>Engines</h3>
{Object.entries(engines).map(([name, engine]) => (
<div key={name} className="engine-control">
<h4>{formatEngineName(name)}</h4>
<p>Status: {engine.status}</p>
<p>Power: {engine.power}%</p>
{engine.status === 'offline' ? (
<button onClick={() => startEngine(name)}>Start</button>
) : (
<>
<input
type="range"
min="0"
max="100"
value={engine.power}
onChange={e => setEnginePower(name, Number(e.target.value))}
/>
<button onClick={() => stopEngine(name)}>Stop</button>
</>
)}
</div>
))}
</div>
<div className="life-support">
<h3>Life Support System</h3>
<p>Oxygen level: {lifeSupportSystem.oxygen}%</p>
<p>Temperature: {lifeSupportSystem.temperature}ยฐC</p>
<p>Pressure: {lifeSupportSystem.pressure} atm</p>
<div className="controls">
<button
onClick={() =>
adjustLifeSupport({
oxygen: lifeSupportSystem.oxygen + 5
})
}
>
Increase oxygen level
</button>
<button
onClick={() =>
adjustLifeSupport({
temperature: lifeSupportSystem.temperature - 1
})
}
>
Lower temperature
</button>
</div>
</div>
</div>
);
}
function formatEngineName(name) {
return name
.replace(/([A-Z])/g, ' $1')
.replace(/^./, str => str.toUpperCase());
}UI component patterns
1. Container / Presentational Pattern
This pattern separates business logic (container) from presentation (presentational component), which increases component reusability and simplifies testing.
// Container component - handles logic and data fetching
function PlanetDataContainer({ planetId, children }) {
const [planet, setPlanet] = useState(null);
const [loading, setLoading] = useState(true);
const [error, setError] = useState(null);
useEffect(() => {
setLoading(true);
fetch(`https://api.planets.com/${planetId}`)
.then(response => {
if (!response.ok) throw new Error('Failed to fetch planet data');
return response.json();
})
.then(data => {
setPlanet(data);
setLoading(false);
})
.catch(err => {
setError(err.message);
setLoading(false);
});
}, [planetId]);
// Call children function with data
return children({ planet, loading, error });
}
// Presentational component - only handles display
function PlanetInfo({ planet, loading, error }) {
if (loading) return <div>Loading planet data...</div>;
if (error) return <div>Error: {error}</div>;
if (!planet) return null;
return (
<div className="planet-info">
<h2>{planet.name}</h2>
<div className="planet-details">
<p>Type: {planet.type}</p>
<p>Diameter: {planet.diameter} km</p>
<p>Distance from Sun: {planet.distanceFromSun} million km</p>
<p>Orbital period: {planet.orbitalPeriod} days</p>
<p>Surface temperature: {planet.surfaceTemperature}ยฐC</p>
</div>
{planet.moons && planet.moons.length > 0 && (
<div className="moons">
<h3>Moons ({planet.moons.length}):</h3>
<ul>
{planet.moons.map(moon => (
<li key={moon.id}>{moon.name}</li>
))}
</ul>
</div>
)}
</div>
);
}
// Usage
function SolarSystemExplorer() {
const [selectedPlanet, setSelectedPlanet] = useState('earth');
return (
<div className="solar-system-explorer">
<h1>Solar System Exploration</h1>
<div className="planet-selector">
<label>Select a planet: </label>
<select
value={selectedPlanet}
onChange={e => setSelectedPlanet(e.target.value)}
>
<option value="mercury">Mercury</option>
<option value="venus">Venus</option>
<option value="earth">Earth</option>
<option value="mars">Mars</option>
<option value="jupiter">Jupiter</option>
<option value="saturn">Saturn</option>
<option value="uranus">Uranus</option>
<option value="neptune">Neptune</option>
</select>
</div>
<PlanetDataContainer planetId={selectedPlanet}>
{({ planet, loading, error }) => (
<PlanetInfo planet={planet} loading={loading} error={error} />
)}
</PlanetDataContainer>
</div>
);
}2. Composition vs Inheritance
React prefers composition over inheritance. This pattern allows creating flexible components through nesting and passing props.
// Base component - Card
function Card({ title, children, footer, className }) {
return (
<div className={`card ${className || ''}`}>
{title && <div className="card-header">{title}</div>}
<div className="card-body">{children}</div>
{footer && <div className="card-footer">{footer}</div>}
</div>
);
}
// Specialized components using composition
function MissionCard({ mission, onComplete }) {
return (
<Card
title={<h3>{mission.name}</h3>}
footer={
<button onClick={() => onComplete(mission.id)}>
Complete mission
</button>
}
className="mission-card"
>
<p><strong>Objective:</strong> {mission.objective}</p>
<p><strong>Status:</strong> {mission.status}</p>
<p><strong>Progress:</strong> {mission.progress}%</p>
<div className="progress-bar">
<div
className="progress"
style={{ width: `${mission.progress}%` }}
/>
</div>
</Card>
);
}
function AstronautCard({ astronaut, onAssign }) {
return (
<Card
title={<h3>{astronaut.name}</h3>}
footer={
<button onClick={() => onAssign(astronaut.id)}>
Assign to mission
</button>
}
className="astronaut-card"
>
<div className="astronaut-info">
<img
src={astronaut.avatar}
alt={astronaut.name}
className="astronaut-avatar"
/>
<div>
<p><strong>Rank:</strong> {astronaut.rank}</p>
<p><strong>Specialization:</strong> {astronaut.specialization}</p>
<p><strong>Missions:</strong> {astronaut.missionCount}</p>
</div>
</div>
</Card>
);
}
// Usage
function Dashboard() {
const missions = [
{ id: 1, name: 'Mars Exploration', objective: 'Explore the surface', status: 'In progress', progress: 65 },
{ id: 2, name: 'ISS Space Station', objective: 'Module maintenance', status: 'Planned', progress: 0 }
];
const astronauts = [
{ id: 1, name: 'John Smith', rank: 'Captain', specialization: 'Pilot', missionCount: 5, avatar: '/avatars/js.png' },
{ id: 2, name: 'Anna Johnson', rank: 'Lieutenant', specialization: 'Engineer', missionCount: 3, avatar: '/avatars/aj.png' }
];
return (
<div className="dashboard">
<h1>Space Center Control Panel</h1>
<section className="missions-section">
<h2>Active Missions</h2>
<div className="missions-grid">
{missions.map(mission => (
<MissionCard
key={mission.id}
mission={mission}
onComplete={id => console.log(`Completed mission ${id}`)}
/>
))}
</div>
</section>
<section className="astronauts-section">
<h2>Available Astronauts</h2>
<div className="astronauts-grid">
{astronauts.map(astronaut => (
<AstronautCard
key={astronaut.id}
astronaut={astronaut}
onAssign={id => console.log(`Assigned astronaut ${id}`)}
/>
))}
</div>
</section>
</div>
);
}3. Headless Components Pattern
This pattern separates the behavioral logic of a component from its appearance, allowing maximum styling flexibility.
// Headless component - contains only logic, no UI
function useTabControl(initialTab = 0) {
const [activeTab, setActiveTab] = useState(initialTab);
function activateTab(index) {
setActiveTab(index);
}
return {
activeTab,
activateTab
};
}
// Usage with any UI
function MissionTabs() {
const tabs = [
{ id: 'overview', label: 'Overview' },
{ id: 'crew', label: 'Crew' },
{ id: 'timeline', label: 'Timeline' },
{ id: 'systems', label: 'Systems' }
];
const { activeTab, activateTab } = useTabControl();
return (
<div className="mission-tabs">
<div className="tabs-header">
{tabs.map((tab, index) => (
<button
key={tab.id}
className={`tab-button ${activeTab === index ? 'active' : ''}`}
onClick={() => activateTab(index)}
>
{tab.label}
</button>
))}
</div>
<div className="tab-content">
{activeTab === 0 && (
<div className="overview-tab">
<h3>Mission Overview</h3>
<p>The Apollo 11 mission was the first crewed mission to the Moon...</p>
</div>
)}
{activeTab === 1 && (
<div className="crew-tab">
<h3>Crew</h3>
<ul>
<li>Neil Armstrong - Commander</li>
<li>Edwin "Buzz" Aldrin - Lunar Module Pilot</li>
<li>Michael Collins - Command Module Pilot</li>
</ul>
</div>
)}
{activeTab === 2 && (
<div className="timeline-tab">
<h3>Timeline</h3>
<div className="timeline">
<div className="timeline-event">
<span className="date">July 16, 1969</span>
<span className="description">Launch from Cape Kennedy</span>
</div>
<div className="timeline-event">
<span className="date">July 20, 1969</span>
<span className="description">Moon landing</span>
</div>
<div className="timeline-event">
<span className="date">July 21, 1969</span>
<span className="description">First step on the Moon</span>
</div>
<div className="timeline-event">
<span className="date">July 24, 1969</span>
<span className="description">Return to Earth</span>
</div>
</div>
</div>
)}
{activeTab === 3 && (
<div className="systems-tab">
<h3>Ship Systems</h3>
<p>Command Module: Columbia</p>
<p>Lunar Module: Eagle</p>
<p>Launch Vehicle: Saturn V</p>
</div>
)}
</div>
</div>
);
}Optimization patterns
1. Memoization
Memoization helps avoid unnecessary renders by remembering the results of expensive computations.
// Component memoization
const MemoizedTelemetryChart = React.memo(function TelemetryChart({ data }) {
// Simulation of expensive computations
const processedData = useMemo(() => {
console.log('Processing telemetry data...');
// Expensive data processing
return data.map(point => ({
x: new Date(point.timestamp).toLocaleTimeString(),
y: calculateAverage(point.readings),
anomaly: detectAnomaly(point.readings)
}));
}, [data]); // Recalculate only when data changes
return (
<div className="telemetry-chart">
<h3>Telemetry Chart</h3>
<div className="chart-container">
{/* Chart with processed data */}
{processedData.map((point, index) => (
<div
key={index}
className={`data-point ${point.anomaly ? 'anomaly' : ''}`}
style={{
height: `${point.y * 2}px`,
backgroundColor: point.anomaly ? 'red' : 'blue'
}}
title={`${point.x}: ${point.y} ${point.anomaly ? '(anomaly)' : ''}`}
/>
))}
</div>
</div>
);
}, (prevProps, nextProps) => {
// Custom props comparison logic
if (prevProps.data.length !== nextProps.data.length) {
return false; // re-render if data size changed
}
// Compare only the last 5 data points
const prevLastFive = prevProps.data.slice(-5);
const nextLastFive = nextProps.data.slice(-5);
for (let i = 0; i < 5; i++) {
if (!prevLastFive[i] || !nextLastFive[i]) continue;
if (
prevLastFive[i].timestamp !== nextLastFive[i].timestamp ||
!arraysEqual(prevLastFive[i].readings, nextLastFive[i].readings)
) {
return false; // re-render if data differs
}
}
return true; // don't re-render
});
// Helper functions
function calculateAverage(readings) {
return readings.reduce((sum, val) => sum + val, 0) / readings.length;
}
function detectAnomaly(readings) {
const avg = calculateAverage(readings);
const threshold = avg * 1.5;
return readings.some(val => val > threshold);
}
function arraysEqual(a, b) {
if (a.length !== b.length) return false;
for (let i = 0; i < a.length; i++) {
if (a[i] !== b[i]) return false;
}
return true;
}2. List virtualization
For large data lists, virtualization allows rendering only the elements that are currently visible on screen.
// Simple virtualization implementation (in real applications
// it's worth using libraries like react-window or react-virtualized)
function VirtualizedAsteroidList({ asteroids, rowHeight = 50, visibleRows = 10 }) {
const [scrollTop, setScrollTop] = useState(0);
const containerRef = useRef();
const totalHeight = asteroids.length * rowHeight;
const startIndex = Math.floor(scrollTop / rowHeight);
const endIndex = Math.min(
startIndex + visibleRows + 1,
asteroids.length
);
const visibleAsteroids = useMemo(() => {
return asteroids.slice(startIndex, endIndex);
}, [asteroids, startIndex, endIndex]);
const handleScroll = useCallback(() => {
if (containerRef.current) {
setScrollTop(containerRef.current.scrollTop);
}
}, []);
return (
<div className="asteroids-list">
<h2>Asteroid Catalog</h2>
<p>Number of asteroids: {asteroids.length}</p>
<div
ref={containerRef}
className="virtual-list-container"
style={{ height: rowHeight * visibleRows, overflow: 'auto' }}
onScroll={handleScroll}
>
<div
className="total-height"
style={{ height: totalHeight }}
>
<div
className="visible-items"
style={{
transform: `translateY(${startIndex * rowHeight}px)`
}}
>
{visibleAsteroids.map(asteroid => (
<div
key={asteroid.id}
className="asteroid-item"
style={{ height: rowHeight }}
>
<span className="name">{asteroid.name}</span>
<span className="diameter">Diameter: {asteroid.diameter} km</span>
<span className="distance">
Distance: {asteroid.distance} million km
</span>
<span
className={`hazard-level ${asteroid.hazardLevel}`}
>
{formatHazardLevel(asteroid.hazardLevel)}
</span>
</div>
))}
</div>
</div>
</div>
</div>
);
}
function formatHazardLevel(level) {
switch (level) {
case 'high': return 'High threat';
case 'medium': return 'Medium threat';
case 'low': return 'Low threat';
default: return 'No threat';
}
}3. Lazy loading
Lazy loading of components allows deferring the loading of parts of the application until they are needed, which can significantly speed up the initial load of the application.
// Lazy loading components
const LazyMarsExplorer = lazy(() => import('./MarsExplorer'));
const LazyJupiterMoons = lazy(() => import('./JupiterMoons'));
const LazySaturnRings = lazy(() => import('./SaturnRings'));
function SolarSystemExplorer() {
const [activeSection, setActiveSection] = useState(null);
return (
<div className="solar-system-explorer">
<h1>Solar System Exploration</h1>
<div className="planet-selector">
<button onClick={() => setActiveSection('mars')}>
Mars Exploration
</button>
<button onClick={() => setActiveSection('jupiter')}>
Jupiter's Moons
</button>
<button onClick={() => setActiveSection('saturn')}>
Saturn's Rings
</button>
</div>
<Suspense fallback={<div className="loading">Loading exploration module...</div>}>
{activeSection === 'mars' && <LazyMarsExplorer />}
{activeSection === 'jupiter' && <LazyJupiterMoons />}
{activeSection === 'saturn' && <LazySaturnRings />}
</Suspense>
</div>
);
}Summary
Design patterns in React provide proven solutions for common programming problems. They allow you to create code that is:
- Reusable - components and logic can be easily used across different parts of the application
- Testable - separation of concerns makes writing tests easier
- Scalable - the application can grow without a drastic increase in complexity
- Maintainable - clear structure and organization make it easier to introduce changes
On our cosmic journey through React, these patterns are like proven interstellar routes that allow you to reach your destination faster and more safely. Experiment with different patterns and choose those that best fit the specific needs of your application.
Code for this lesson: App.jsx
import React, { useState, useEffect, useCallback } from 'react';
// Custom Hook: useLocalStorage
function useLocalStorage(key, initialValue) {
// State for storing values
const [storedValue, setStoredValue] = useState(() => {
try {
const item = window.localStorage.getItem(key);
return item ? JSON.parse(item) : initialValue;
} catch (error) {
console.log('Error reading localStorage:', error);
return initialValue;
}
});
// Function for updating values
const setValue = useCallback((value) => {
setStoredValue((prev) => (value instanceof Function ? value(prev) : value));
}, []);
// Save to localStorage on every change
useEffect(() => {
try {
window.localStorage.setItem(key, JSON.stringify(storedValue));
} catch (error) {
console.log('Error saving to localStorage:', error);
}
}, [key, storedValue]);
return [storedValue, setValue];
}
// Custom Hook: useToggle
function useToggle(initialValue = false) {
const [value, setValue] = useState(initialValue);
const toggle = useCallback(() => {
setValue(v => !v);
}, []);
const setTrue = useCallback(() => {
setValue(true);
}, []);
const setFalse = useCallback(() => {
setValue(false);
}, []);
return { value, toggle, setTrue, setFalse };
}
// Custom Hook: useCounter
function useCounter(initialValue = 0, step = 1) {
const [count, setCount] = useState(initialValue);
const increment = useCallback(() => {
setCount(c => c + step);
}, [step]);
const decrement = useCallback(() => {
setCount(c => c - step);
}, [step]);
const reset = useCallback(() => {
setCount(initialValue);
}, [initialValue]);
return { count, increment, decrement, reset, setCount };
}
// Custom hooks demonstration
function CustomHooksDemo() {
// useLocalStorage - storing settings
const [username, setUsername] = useLocalStorage('username', '');
const [settings, setSettings] = useLocalStorage('settings', {
darkMode: true,
notifications: true,
language: 'pl'
});
// useToggle - toggles
const darkMode = useToggle(settings.darkMode);
const showPanel = useToggle(false);
const isEditing = useToggle(false);
// useCounter - counters
const visits = useCounter(0);
const score = useCounter(100, 10);
// Effect for synchronizing with localStorage
useEffect(() => {
setSettings(prev => ({ ...prev, darkMode: darkMode.value }));
}, [darkMode.value, setSettings]);
const containerStyle = {
minHeight: '100vh',
background: darkMode.value
? 'linear-gradient(135deg, #1a1a2e 0%, #16213e 100%)'
: 'linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%)',
padding: '30px',
fontFamily: "'Segoe UI', sans-serif",
color: darkMode.value ? '#fff' : '#1a1a2e',
transition: 'all 0.5s ease',
};
const cardStyle = {
background: darkMode.value ? 'rgba(255,255,255,0.05)' : 'rgba(0,0,0,0.05)',
borderRadius: '15px',
padding: '25px',
marginBottom: '25px',
border: '1px solid ' + (darkMode.value ? 'rgba(255,255,255,0.1)' : 'rgba(0,0,0,0.1)'),
};
return (
<div style={containerStyle}>
<header style={{ textAlign: 'center', marginBottom: '40px' }}>
<h1 style={{ color: '#00d4ff', fontSize: '2.5em' }}>
Custom Hooks Demo
</h1>
<p style={{ opacity: 0.7 }}>Creating custom hooks in React</p>
</header>
<div style={{ maxWidth: '900px', margin: '0 auto' }}>
{/* useLocalStorage Demo */}
<div style={cardStyle}>
<h2 style={{ color: '#ffd700', marginBottom: '20px' }}>
useLocalStorage
</h2>
<p style={{ marginBottom: '15px' }}>
Stores data in localStorage with automatic synchronization
</p>
<div style={{ marginBottom: '15px' }}>
<label style={{ display: 'block', marginBottom: '5px' }}>
Username (saved in localStorage):
</label>
<input
type="text"
value={username}
onChange={(e) => setUsername(e.target.value)}
placeholder="Enter your name"
style={{
padding: '10px 15px',
borderRadius: '8px',
border: '2px solid #00d4ff',
background: 'transparent',
color: 'inherit',
width: '300px',
}}
/>
</div>
<p style={{ fontSize: '14px', opacity: 0.7 }}>
Refresh the page - the value will be preserved!
</p>
</div>
{/* useToggle Demo */}
<div style={cardStyle}>
<h2 style={{ color: '#ffd700', marginBottom: '20px' }}>
useToggle
</h2>
<div style={{ display: 'flex', gap: '20px', flexWrap: 'wrap' }}>
<div style={{ flex: '1', minWidth: '200px' }}>
<p style={{ marginBottom: '10px' }}>Dark Mode:</p>
<button
onClick={darkMode.toggle}
style={{
padding: '10px 20px',
background: darkMode.value ? '#4CAF50' : '#f44336',
color: 'white',
border: 'none',
borderRadius: '8px',
cursor: 'pointer',
}}
>
{darkMode.value ? 'ON' : 'OFF'}
</button>
</div>
<div style={{ flex: '1', minWidth: '200px' }}>
<p style={{ marginBottom: '10px' }}>Show Panel:</p>
<button
onClick={showPanel.toggle}
style={{
padding: '10px 20px',
background: showPanel.value ? '#4CAF50' : '#9e9e9e',
color: 'white',
border: 'none',
borderRadius: '8px',
cursor: 'pointer',
}}
>
{showPanel.value ? 'Hide' : 'Show'}
</button>
{showPanel.value && (
<div style={{
marginTop: '15px',
padding: '15px',
background: 'rgba(0,212,255,0.1)',
borderRadius: '8px',
}}>
Panel visible!
</div>
)}
</div>
</div>
</div>
{/* useCounter Demo */}
<div style={cardStyle}>
<h2 style={{ color: '#ffd700', marginBottom: '20px' }}>
useCounter
</h2>
<div style={{ display: 'flex', gap: '40px', flexWrap: 'wrap' }}>
<div>
<p style={{ marginBottom: '10px' }}>Visits (step: 1):</p>
<div style={{ display: 'flex', alignItems: 'center', gap: '10px' }}>
<button onClick={visits.decrement} style={btnStyle}>-</button>
<span style={{ fontSize: '2em', minWidth: '60px', textAlign: 'center' }}>
{visits.count}
</span>
<button onClick={visits.increment} style={btnStyle}>+</button>
<button onClick={visits.reset} style={{ ...btnStyle, background: '#ff9800' }}>
Reset
</button>
</div>
</div>
<div>
<p style={{ marginBottom: '10px' }}>Score (step: 10):</p>
<div style={{ display: 'flex', alignItems: 'center', gap: '10px' }}>
<button onClick={score.decrement} style={btnStyle}>-10</button>
<span style={{ fontSize: '2em', minWidth: '80px', textAlign: 'center' }}>
{score.count}
</span>
<button onClick={score.increment} style={btnStyle}>+10</button>
<button onClick={score.reset} style={{ ...btnStyle, background: '#ff9800' }}>
Reset
</button>
</div>
</div>
</div>
</div>
</div>
<footer style={{ textAlign: 'center', marginTop: '40px', opacity: 0.7 }}>
<p>Custom hooks allow extracting and sharing logic</p>
</footer>
</div>
);
}
const btnStyle = {
padding: '10px 20px',
background: '#00d4ff',
color: '#000',
border: 'none',
borderRadius: '8px',
cursor: 'pointer',
fontWeight: 'bold',
fontSize: '16px',
};
export default CustomHooksDemo;Docs entries used in this lesson
Spotted a mistake in this lesson?
Check yourself
Answer the questions from this lesson. Pick an answer to see right away whether it is correct.
1. Which of the following is a rule for using hooks?
2. What characterizes the Render Props pattern?
These are 2 of 4 questions for this lesson. Solve the rest in the game.
Hands-on tasks in the game
- Code editor
Custom hook for the space station
- Horizontal ordering
Arrange the syntax for calling a Higher-Order Component:
- Vertical ordering
Arrange the custom hook structure:
- Code editor
Advanced data fetching hook
- Code editor
HOC with Authorization and Monitoring
- Click in order
Arrange the correct Higher-Order Component syntax:
- Code editor
Render Props for Sensor Network
Tasks after this lesson
- QuestionIntroduction: Hook Rules
- Coding taskPractice: Custom Hook
- Put in orderIntroduction: Higher Order Components (HOC)
- Put in orderCustom Hook Pattern Flow
- Coding taskPractice: useFetch Hook
- QuestionIntroduction: Render Props Pattern
- QuestionIntroduction: Compound Components
- Coding taskIntroduction: Practice: HOC Pattern
- Click in orderIntroduction: HOC Syntax in React
- QuestionContainer vs Presentational
- Coding taskIntroduction: Practice: Render Props