JavaScript and React course · Module 6: React Router
Passing State Through Locations in Intergalactic Communication
In this lesson9
On a cosmic journey, we sometimes need to send important data from one sector of the space station to another. In React applications using React Router, we similarly pass state (data) between different pages using the location state mechanism. Let's see how to use this mechanism to improve our intergalactic communication.
What is Location State?
Location state is a mechanism in React Router that allows passing data during navigation between different paths without the need to use URL parameters, cookies, or global application state. This data is not visible in the URL, but is available on the target page.
Passing State Through Link
The simplest way to pass data through location state is to use the Link component with an additional state parameter:
import { Link } from 'react-router-dom';
function PlanetList() {
const planets = [
{ id: 1, name: 'Mars', atmosphere: 'Thin, mainly CO2', temperature: 'From -125°C to 20°C' },
{ id: 2, name: 'Venus', atmosphere: 'Dense, mainly CO2', temperature: 'Average 462°C' },
{ id: 3, name: 'Titan', atmosphere: 'Dense, nitrogen and methane', temperature: 'Average -179°C' }
];
return (
<div className="planet-explorer">
<h1>Planet Exploration</h1>
<ul className="planet-list">
{planets.map(planet => (
<li key={planet.id}>
<Link
to={`/planet/${planet.id}`}
state={{ planetData: planet }}
>
Explore {planet.name}
</Link>
</li>
))}
</ul>
</div>
);
}In the example above, clicking a link will navigate the user to page /planet/1 (for Mars) and simultaneously pass the planetData object containing all information about the planet.
Receiving State in the Target Component
To read the passed state in the target component, we use the useLocation hook:
import { useParams, useLocation } from 'react-router-dom';
function PlanetDetails() {
// Get the parameter from the URL
const { id } = useParams();
// Get the location object, which contains the passed state
const location = useLocation();
// Extract the planet data from the location state, with a fallback to an empty object
const { planetData } = location.state || {};
// If we didn't receive planet data, we can show an error message
// or try to fetch data based on the ID
if (!planetData) {
return (
<div className="error-message">
<h2>No Planet Data</h2>
<p>Failed to load data for planet with ID: {id}</p>
<Link to="/">Return to planet list</Link>
</div>
);
}
return (
<div className="planet-details">
<h1>Planet Details: {planetData.name}</h1>
<div className="planet-info">
<p><strong>Atmosphere:</strong> {planetData.atmosphere}</p>
<p><strong>Temperature:</strong> {planetData.temperature}</p>
</div>
<Link to="/">Return to planet list</Link>
</div>
);
}Programmatic State Passing
We can also pass state programmatically using the useNavigate hook:
import { useNavigate } from 'react-router-dom';
function MissionControl() {
const navigate = useNavigate();
const startMission = (mission) => {
// Perform some operations before navigating to the next page
const missionData = {
...mission,
startDate: new Date().toISOString(),
commander: 'Captain Alex Chen',
status: 'In Progress'
};
// Redirect to the mission page with data
navigate(`/mission/${mission.id}`, {
state: { missionData }
});
};
return (
<div className="mission-control">
<h1>Mission Command Center</h1>
<div className="mission-list">
<div className="mission-card">
<h3>Mission: Mars Exploration</h3>
<p>Objective: Soil sample research</p>
<button onClick={() => startMission({
id: 'mars-exploration-1',
name: 'Mars Exploration',
objective: 'Soil sample research'
})}>
Start Mission
</button>
</div>
<div className="mission-card">
<h3>Mission: Satellite Station</h3>
<p>Objective: Communication systems repair</p>
<button onClick={() => startMission({
id: 'satellite-repair-1',
name: 'Satellite Station',
objective: 'Communication systems repair'
})}>
Start Mission
</button>
</div>
</div>
</div>
);
}Advanced Use Cases
1. Passing Previous Location Information
We can use location state to remember the page the user came from:
function SecureArea() {
const navigate = useNavigate();
const { user } = useAuth();
useEffect(() => {
if (!user) {
// Redirect to login with information about the current path
navigate('/login', {
state: { from: location.pathname },
replace: true
});
}
}, [user, navigate, location]);
return (
<div className="secure-area">
<h1>Secure Section of the Spaceship</h1>
{/* Secure section content */}
</div>
);
}
// In the login component
function Login() {
const location = useLocation();
const navigate = useNavigate();
// Get the original path the user tried to access
const from = location.state?.from || '/dashboard';
const handleLogin = async (credentials) => {
const success = await performLogin(credentials);
if (success) {
// After login, return to the original page
navigate(from, { replace: true });
}
};
// Rest of the login component...
}2. Passing Form Data in a Multi-step Process
Another advanced case is preserving form data during navigation in a multi-step process:
function SpaceshipConfigStep1() {
const [config, setConfig] = useState({
name: '',
type: 'exploration',
crew: 4
});
const navigate = useNavigate();
const handleNext = () => {
// Form validation...
// Navigate to the next step with data
navigate('/config/step2', {
state: { config }
});
};
return (
<div className="config-form">
<h2>Spaceship Configuration - Step 1</h2>
<form onSubmit={e => { e.preventDefault(); handleNext(); }}>
<div className="form-field">
<label htmlFor="name">Ship name:</label>
<input
id="name"
value={config.name}
onChange={e => setConfig({...config, name: e.target.value})}
required
/>
</div>
<div className="form-field">
<label htmlFor="type">Mission type:</label>
<select
id="type"
value={config.type}
onChange={e => setConfig({...config, type: e.target.value})}
>
<option value="exploration">Exploration</option>
<option value="science">Scientific Research</option>
<option value="mining">Resource Mining</option>
</select>
</div>
<div className="form-field">
<label htmlFor="crew">Crew size:</label>
<input
id="crew"
type="number"
min="1"
max="10"
value={config.crew}
onChange={e => setConfig({...config, crew: parseInt(e.target.value)})}
required
/>
</div>
<button type="submit">Next</button>
</form>
</div>
);
}
function SpaceshipConfigStep2() {
const location = useLocation();
const navigate = useNavigate();
// Get configuration from the previous step
const { config: prevConfig } = location.state || { config: null };
// If we don't have configuration, redirect back
useEffect(() => {
if (!prevConfig) {
navigate('/config/step1', { replace: true });
}
}, [prevConfig, navigate]);
// Initialize state with data from the previous step
const [config, setConfig] = useState({
...prevConfig,
engines: 'ion',
fuelCapacity: 5000,
lifeSupport: 'advanced'
});
const handleFinish = () => {
// Complete configuration from both steps
const finalConfig = {
...config
};
// Finalize configuration
navigate('/config/summary', {
state: { finalConfig }
});
};
if (!prevConfig) return null; // Don't render anything until the redirect executes
return (
<div className="config-form">
<h2>Spaceship Configuration - Step 2</h2>
<form onSubmit={e => { e.preventDefault(); handleFinish(); }}>
{/* Second set of form fields */}
<div className="form-actions">
<button
type="button"
onClick={() => navigate(-1)}
>
Back
</button>
<button type="submit">Finish</button>
</div>
</form>
</div>
);
}The replace Function and Browser History
In the examples, we used the replace: true parameter. This is an important option that affects browser history behavior:
- When
replace: false(default) - adds a new page to history. The user can return to the previous page with the "Back" button. - When
replace: true- replaces the current page in history. When the user presses the "Back" button, they will return to the page before the last redirect.
// Adds a new page to browser history
navigate('/dashboard', { state: { data: 'example' } });
// Replaces the current page in history
navigate('/dashboard', {
state: { data: 'example' },
replace: true
});The replace option is particularly useful in login processes, where after redirecting the user to the login page and back, we don't want them to be able to return to the login page using the "Back" button.
Limitations and Alternatives
Location state has certain limitations:
- Not persistent - data is lost on page refresh
- Limited size - we shouldn't pass very large objects
- Not visible in URL - which can be an advantage (privacy) or disadvantage (can't remember/share the exact state)
Alternative methods of passing data between pages:
URL parameters: Data is visible in the URL address
// Passing through URL navigate(`/planet/mars?atmosphere=thin&temperature=-60`); // Reading const { search } = useLocation(); const queryParams = new URLSearchParams(search); const atmosphere = queryParams.get('atmosphere'); // 'thin'Global application state: State management using Context API, Redux, Zustand, etc.
// Saving data dispatch(setCurrentPlanet({ name: 'Mars', atmosphere: 'thin' })); navigate('/planet-details'); // Reading data const currentPlanet = useSelector(state => state.planets.current);Local storage: sessionStorage, localStorage
// Saving data sessionStorage.setItem('planetData', JSON.stringify({ name: 'Mars' })); navigate('/planet-details'); // Reading data const planetData = JSON.parse(sessionStorage.getItem('planetData') || '{}');
Best Practices
- Minimal data scope: Pass only necessary data
- Data validation: Always check if data exists before using it
- Provide a fallback: Have a plan B when data is not available
- Avoid sensitive data: Don't pass confidential information through location state
- Use type safety: If using TypeScript, define types for data in location state
Summary
Passing state through locations in React Router is like intergalactic communication - we can send important data between different "stations" (pages) of our application without having to store them globally.
This technique is particularly useful in cases such as:
- Passing object details to a detail page
- Remembering the original location during authentication redirects
- Preserving form state in multi-step processes
- Passing messages and notifications between pages (e.g., "Operation completed successfully")
When choosing between location state and other data passing methods, always consider the persistence, visibility, and size of the data to choose the best approach for the specific use case.
Code for this lesson: App.jsx
import React from 'react';
import { BrowserRouter, Routes, Route, Link, Navigate, useNavigate } from 'react-router-dom';
// 404 page
function NotFoundPage() {
const navigate = useNavigate();
return (
<div className="page not-found">
<div className="error-code">404</div>
<h1>Lost in space</h1>
<p>This page does not exist in our universe.</p>
<div className="actions">
<button onClick={() => navigate('/')}>Go home</button>
<button onClick={() => navigate(-1)}>← Back</button>
</div>
</div>
);
}
// Home page
function HomePage() {
return (
<div className="page">
<h1>Home page</h1>
<p>Welcome to the control center!</p>
</div>
);
}
// Profile page (redirect from old URL)
function ProfilePage() {
return (
<div className="page">
<h1>User profile</h1>
<p>Your profile data.</p>
</div>
);
}
// Settings page
function SettingsPage() {
return (
<div className="page">
<h1>Settings</h1>
<p>System configuration.</p>
</div>
);
}
// Old page (redirect)
function OldPage() {
return <Navigate to="/new-page" replace />;
}
function NewPage() {
return (
<div className="page">
<h1>New page</h1>
<p>You have been redirected from the old page!</p>
</div>
);
}
function Navigation() {
return (
<nav>
<Link to="/">Home</Link>
<Link to="/profile">Profile</Link>
<Link to="/settings">Settings</Link>
<Link to="/old-page">Old page (redirect)</Link>
<Link to="/non-existent">Non-existent</Link>
</nav>
);
}
function App() {
return (
<BrowserRouter>
<div className="app">
<Navigation />
<Routes>
<Route path="/" element={<HomePage />} />
<Route path="/profile" element={<ProfilePage />} />
<Route path="/settings" element={<SettingsPage />} />
{/* Redirect from old URL to new */}
<Route path="/old-page" element={<Navigate to="/new-page" replace />} />
<Route path="/new-page" element={<NewPage />} />
{/* Redirect from /user to /profile */}
<Route path="/user" element={<Navigate to="/profile" />} />
<Route path="/user/:id" element={<Navigate to="/profile" />} />
{/* Catch-all route - 404 */}
<Route path="*" element={<NotFoundPage />} />
</Routes>
</div>
</BrowserRouter>
);
}
export default App;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. How can you pass data to the next page using the Link component?
2. Which hook would you use to read data passed through location state?
Hands-on tasks in the game
- Click in order
Arrange the syntax for programmatically passing state using navigate: