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

  1. When do you prefer URL params over context for passing data?
  2. What should you consider when encoding data in the URL?
Show answers
  1. Use URL params for shareable/bookmarkable state; use context for app-wide or ephemeral values.
  2. Encode special characters, avoid sensitive information, and keep URLs human-readable.

Exercises

  1. Pass two parameters via the hash (e.g., #/greet/Ada/42) and parse both.
  2. Mirror a piece of state to the URL so reload preserves it.
  3. Replace hash routing with a small history API router and compare behavior.