React - Passing Data Between Screens
Overview
Estimated time: 20–30 minutes
Pass data between screens using URL parameters (hash-based) or shared context for app-wide values.
Try it: Hash Param Router
View source
const { useEffect, useState } = React;
function useHash(){
const [hash, setHash] = useState(() => window.location.hash || '#/');
useEffect(() => {
const onHash = () => setHash(window.location.hash || '#/');
window.addEventListener('hashchange', onHash);
return () => window.removeEventListener('hashchange', onHash);
}, []);
return hash;
}
function App(){
const hash = useHash();
// pattern: #/greet/Ada
const parts = hash.split('/');
const name = parts[2] || 'World';
return (
<div>
<nav>
<a href="#/greet/Ada">Greet Ada</a> | <a href="#/greet/Grace">Greet Grace</a>
</nav>
<h3>Hello, {name}!</h3>
</div>
);
}
ReactDOM.createRoot(document.getElementById('try-screens')).render(<App />);
Syntax primer
- Pass simple values via URL segments; parse in your router/view.
- Use context for app-wide values (e.g., current user) that aren’t convenient to pass via URL.
Common pitfalls
- Forgetting to URL-encode values when using arbitrary strings.
Checks for Understanding
- When do you prefer URL params over context for passing data?
- What should you consider when encoding data in the URL?
Show answers
- Use URL params for shareable/bookmarkable state; use context for app-wide or ephemeral values.
- Encode special characters, avoid sensitive information, and keep URLs human-readable.
Exercises
- Pass two parameters via the hash (e.g.,
#/greet/Ada/42
) and parse both. - Mirror a piece of state to the URL so reload preserves it.
- Replace hash routing with a small history API router and compare behavior.