Brilliant
Staff member
- Joined
- Dec 31, 2024
- Messages
- 373
- Reaction score
- 7
- Points
- 18
- User icon
- <svg xmlns="http://www.w3.org/2000/svg" height="14" width="15.75" viewBox="0 0 576 512"><!--!Font Awesome Free 6.7.2 by @fontawesome - https://fontawesome.com License - https://fontawesome.com/license/free Copyright 2025 Fonticons, Inc.--><path fill="#63E6BE" d="M309 106c11.4-7 19-19.7 19-34c0-22.1-17.9-40-40-40s-40 17.9-40 40c0 14.4 7.6 27 19 34L209.7 220.6c-9.1 18.2-32.7 23.4-48.6 10.7L72 160c5-6.7 8-15 8-24c0-22.1-17.9-40-40-40S0 113.9 0 136s17.9 40 40 40c.2 0 .5 0 .7 0L86.4 427.4c5.5 30.4 32 52.6 63 52.6l277.2 0c30.9 0 57.4-22.1 63-52.6L535.3 176c.2 0 .5 0 .7 0c22.1 0 40-17.9 40-40s-17.9-40-40-40s-40 17.9-40 40c0 9 3 17.3 8 24l-89.1 71.3c-15.9 12.7-39.5 7.5-48.6-10.7L309 106z"/></svg>
In Next.js 15 (or earlier versions), you can pass data between components during route changes using several techniques, such as URL query parameters, the router.push method with state, or shared state management libraries like Context or Redux.
Here are the most common ways to handle this:
---
1. Using URL Query Parameters
You can pass data in the query string and retrieve it in the destination component using useRouter.
Example: Passing Query Parameters
Source Component:
Destination Component:
---
2. Using Router State (router.push with state)
Starting in Next.js 13+, you can pass state with router.push. This state is not reflected in the URL.
Example: Using Router State
Source Component:
Destination Component:
---
3. Using Context API
The React Context API is great for sharing state across components without relying on props or query parameters.
Example: Using Context API
Context Setup (context/UserContext.js):
Source Component:
Destination Component:
Wrap Your App in UserProvider (_app.js):
---
4. Using Local Storage or Session Storage
For small-scale data, you can use localStorage or sessionStorage to persist data across routes.
Example:
Source Component:
Destination Component:
---
Each method is suited for different use cases:
Use query parameters for sharing data through the URL.
Use router state for lightweight, temporary data not requiring persistence.
Use Context API for global state management.
Use localStorage/sessionStorage for persistent data across page reloads.
Here are the most common ways to handle this:
---
1. Using URL Query Parameters
You can pass data in the query string and retrieve it in the destination component using useRouter.
Example: Passing Query Parameters
Source Component:
JavaScript:
import { useRouter } from 'next/router';
export default function SourceComponent() {
const router = useRouter();
const handleNavigate = () => {
router.push({
pathname: '/destination',
query: { name: 'John Doe', age: 30 }
});
};
return <button onClick={handleNavigate}>Go to Destination</button>;
}
Destination Component:
JavaScript:
import { useRouter } from 'next/router';
export default function DestinationComponent() {
const router = useRouter();
const { name, age } = router.query;
return (
<div>
<h1>Received Data</h1>
<p>Name: {name}</p>
<p>Age: {age}</p>
</div>
);
}
---
2. Using Router State (router.push with state)
Starting in Next.js 13+, you can pass state with router.push. This state is not reflected in the URL.
Example: Using Router State
Source Component:
JavaScript:
import { useRouter } from 'next/router';
export default function SourceComponent() {
const router = useRouter();
const handleNavigate = () => {
router.push('/destination', undefined, { shallow: true, state: { user: { name: 'John', age: 30 } } });
};
return <button onClick={handleNavigate}>Go to Destination</button>;
}
Destination Component:
JavaScript:
import { useRouter } from 'next/router';
import { useEffect, useState } from 'react';
export default function DestinationComponent() {
const router = useRouter();
const [state, setState] = useState(null);
useEffect(() => {
const { state } = router; // Access the state passed during navigation
setState(state);
}, [router]);
return (
<div>
<h1>Received Data</h1>
{state && (
<>
<p>Name: {state.user.name}</p>
<p>Age: {state.user.age}</p>
</>
)}
</div>
);
}
---
3. Using Context API
The React Context API is great for sharing state across components without relying on props or query parameters.
Example: Using Context API
Context Setup (context/UserContext.js):
JavaScript:
import { createContext, useState } from 'react';
export const UserContext = createContext();
export function UserProvider({ children }) {
const [user, setUser] = useState(null);
return (
<UserContext.Provider value={{ user, setUser }}>
{children}
</UserContext.Provider>
);
}
Source Component:
JavaScript:
import { useContext } from 'react';
import { UserContext } from '../context/UserContext';
import { useRouter } from 'next/router';
export default function SourceComponent() {
const { setUser } = useContext(UserContext);
const router = useRouter();
const handleNavigate = () => {
setUser({ name: 'John Doe', age: 30 });
router.push('/destination');
};
return <button onClick={handleNavigate}>Go to Destination</button>;
}
Destination Component:
JavaScript:
import { useContext } from 'react';
import { UserContext } from '../context/UserContext';
export default function DestinationComponent() {
const { user } = useContext(UserContext);
return (
<div>
<h1>Received Data</h1>
{user ? (
<>
<p>Name: {user.name}</p>
<p>Age: {user.age}</p>
</>
) : (
<p>No data received</p>
)}
</div>
);
}
Wrap Your App in UserProvider (_app.js):
JavaScript:
import { UserProvider } from '../context/UserContext';
export default function App({ Component, pageProps }) {
return (
<UserProvider>
<Component {...pageProps} />
</UserProvider>
);
}
---
4. Using Local Storage or Session Storage
For small-scale data, you can use localStorage or sessionStorage to persist data across routes.
Example:
Source Component:
JavaScript:
import { useRouter } from 'next/router';
export default function SourceComponent() {
const router = useRouter();
const handleNavigate = () => {
localStorage.setItem('user', JSON.stringify({ name: 'John', age: 30 }));
router.push('/destination');
};
return <button onClick={handleNavigate}>Go to Destination</button>;
}
Destination Component:
JavaScript:
import { useEffect, useState } from 'react';
export default function DestinationComponent() {
const [user, setUser] = useState(null);
useEffect(() => {
const userData = localStorage.getItem('user');
if (userData) {
setUser(JSON.parse(userData));
}
}, []);
return (
<div>
<h1>Received Data</h1>
{user ? (
<>
<p>Name: {user.name}</p>
<p>Age: {user.age}</p>
</>
) : (
<p>No data received</p>
)}
</div>
);
}
---
Each method is suited for different use cases:
Use query parameters for sharing data through the URL.
Use router state for lightweight, temporary data not requiring persistence.
Use Context API for global state management.
Use localStorage/sessionStorage for persistent data across page reloads.