Code To Learn logo

Code To Learn

M4: Routes & Navigation

L12: Module 4 Review

Comprehensive review of React Router concepts and patterns

Congratulations on completing Module 4! Let's review everything you've learned about React Router and client-side navigation.

What You've Learned

Over 11 lessons, you've mastered:

  • ✅ Installing and configuring React Router
  • ✅ Setting up BrowserRouter and Routes
  • ✅ Creating page components
  • ✅ Dynamic routes with URL parameters
  • ✅ Extracting parameters with useParams
  • ✅ Fetching data based on route params
  • ✅ Component extraction and composition
  • ✅ Navigation with Link components
  • ✅ Handling 404 errors
  • ✅ Programmatic navigation with useNavigate

Core Concepts Summary

1. React Router Setup

// Router.jsx - Central routing configuration
import { BrowserRouter, Routes, Route } from 'react-router-dom';

export default function Router() {
  return (
    <BrowserRouter>
      <Routes>
        <Route path="/" element={<HomePage />} />
        <Route path="/listing/:id" element={<ListingDetailsPage />} />
        <Route path="*" element={<NotFoundPage />} />
      </Routes>
    </BrowserRouter>
  );
}

Key components:

  • BrowserRouter - Provides routing context
  • Routes - Container for route definitions
  • Route - Maps paths to components

2. Dynamic Routes

// Route with parameter
<Route path="/listing/:id" element={<ListingDetailsPage />} />

// Extract parameter in component
import { useParams } from 'react-router-dom';

function ListingDetailsPage() {
  const { id } = useParams(); // id = "42" from /listing/42
  
  useEffect(() => {
    fetch(`/api/listings/${id}`)
      .then(res => res.json())
      .then(setListing);
  }, [id]); // Re-fetch when ID changes
}

Remember:

  • Parameters are always strings
  • Include param in useEffect dependencies
  • Use template literals for dynamic URLs

3. Navigation

For programmatic navigation:

import { useNavigate } from 'react-router-dom';

function Component() {
  const navigate = useNavigate();

  // After form submit
  const handleSubmit = async () => {
    await submitForm();
    navigate('/success');
  };

  // Go back
  const goBack = () => navigate(-1);

  // With state
  const checkout = () => {
    navigate('/checkout', {
      state: { items: cart }
    });
  };
}

Common Patterns

Best Practices

Routing Best Practices

  1. Route Organization

    // ✅ Keep routes in one central file
    // src/components/Router.jsx
    
    // ❌ Don't scatter routes across files
  2. Route Order

    <Routes>
      {/* Specific routes first */}
      <Route path="/listing/new" element={<CreateListing />} />
      
      {/* Dynamic routes next */}
      <Route path="/listing/:id" element={<Details />} />
      
      {/* Catch-all last */}
      <Route path="*" element={<NotFound />} />
    </Routes>
  3. URL Design

    // ✅ Good - clear, RESTful
    /listings           // List all
    /listing/:id        // View one
    /listing/:id/edit   // Edit one
    
    // ❌ Bad - unclear
    /view?id=42
    /edit-listing-42

Component Best Practices

  1. Separate Concerns

    // ✅ Page handles data, Card handles display
    function ListingDetailsPage() {
      const { id } = useParams();
      const listing = useFetch(`/api/listings/${id}`);
      return <ListingDetailsCard listing={listing} />;
    }
  2. Error Handling

    // ✅ Always handle loading and errors
    if (isLoading) return <Spinner />;
    if (error) return <ErrorMessage error={error} />;
    return <Content data={data} />;
  3. Cleanup

    // ✅ Always cleanup side effects
    useEffect(() => {
      const controller = new AbortController();
      
      fetch(url, { signal: controller.signal })
        .then(/* ... */);
      
      return () => controller.abort();
    }, [id]);

Common Pitfalls

React Router Hooks Quick Reference

HookPurposeExample
useParamsGet URL parametersconst { id } = useParams()
useNavigateProgrammatic navigationnavigate('/home')
useLocationGet current locationconst location = useLocation()
useSearchParamsQuery string paramsconst [params] = useSearchParams()
useMatchCheck route matchconst match = useMatch('/listing/:id')

Testing Your Knowledge

Can you answer these?

  1. What's the difference between <Link> and <a> tags?
  2. Why must parameters be included in useEffect dependencies?
  3. When should you use useNavigate instead of Link?
  4. What does the * path match in routes?
  5. How do you prevent race conditions in data fetching?

Check Your Understanding

If you can answer all these questions, you've mastered React Router! If not, review the relevant lessons.

What You Can Build Now

With Module 4 complete, you can build:

  • ✅ Multi-page single-page applications (SPAs)
  • ✅ Dynamic routes with URL parameters
  • ✅ Protected/authenticated routes
  • ✅ Nested navigation structures
  • ✅ Form flows with navigation
  • ✅ Professional 404 error pages
  • ✅ Complex navigation patterns

Module 4 Stats

What you built:

  • 7 components (HomePage, DetailsPage, NotFoundPage, Router, Card, etc.)
  • 13 routes (including dynamic routes)
  • Multiple navigation patterns
  • Complete booking platform navigation

Lines of code: ~1,500 lines across all lessons

Concepts mastered: 15+ routing concepts

What's Next?

In Lesson 13, you'll put everything together in a comprehensive challenge! Build a complete routing feature with search, favorites, and breadcrumbs. Time to test your skills! 🚀

Module 4 Complete! 🎉

You've mastered React Router! You know how to build complex, multi-page applications with professional navigation. Great work!