Skip to main content

Build a Local Train Journey Planner App Using React.js — Manage State with Hooks and Context API


Planning daily and weekend city commutes can be frustrating — especially when juggling multiple train routes or frequent schedule changes. In this guide, we’ll build a simple Local Train Journey Planner App using React.js, where users can create, view, and manage their train journeys.

You’ll learn how to use React Hooks to manage state, share state across components using the React Context API, and understand how React compares to other modern front-end frameworks like Angular and Vue.js.

This tutorial focuses purely on the front-end, so you can easily integrate it with your backend later if you choose to extend it.


🚀 What We’ll Build

We’re going to create a React app that allows users to:

  • Add new train journeys (source, destination, and date).

  • View a list of planned journeys.

  • Delete or update existing trips.

  • Manage the state locally using React Hooks and Context API.

This app will simulate a real-world journey planner UI, ideal for local train commutes during the workweek or weekends.


🧠 Understanding React.js

React.js is a popular JavaScript library for building user interfaces. Developed by Facebook, it allows developers to create dynamic and fast front-end applications using components and declarative programming.

The two key React concepts we’ll use in this app are:

  • React Hooks (useState, useContext, useEffect) for managing and reacting to state changes.

  • React Context API for sharing data between components without prop drilling.


🏗️ Setting Up the React App

Let’s start by setting up a new React project.

npx create-react-app journey-planner cd journey-planner npm start

This will spin up a development server at http://localhost:3000/ and display the default React welcome screen.

Now, let’s clean up the project:

  • Remove unnecessary files in /src such as App.test.js, logo.svg, and setupTests.js.

  • Keep only App.js, index.js, and App.css.


⚙️ Setting Up State with React Hooks

Let’s create our Journey Context to manage the shared journey data.

🧩 Step 1: Create the Journey Context

src/JourneyContext.js

import React, { createContext, useState } from 'react'; export const JourneyContext = createContext(); export const JourneyProvider = ({ children }) => { const [journeys, setJourneys] = useState([]); const addJourney = (journey) => { setJourneys([...journeys, journey]); }; const removeJourney = (index) => { setJourneys(journeys.filter((_, i) => i !== index)); }; return ( <JourneyContext.Provider value={{ journeys, addJourney, removeJourney }}> {children} </JourneyContext.Provider> ); };

This context stores:

  • An array of journeys

  • Functions to add and remove journeys


🧭 Step 2: Create the Main App Structure

src/App.js

import React from 'react'; import { JourneyProvider } from './JourneyContext'; import JourneyForm from './components/JourneyForm'; import JourneyList from './components/JourneyList'; import './App.css'; function App() { return ( <JourneyProvider> <div className="App"> <h1>🚆 Local Train Journey Planner</h1> <JourneyForm /> <JourneyList /> </div> </JourneyProvider> ); } export default App;

We wrap everything inside JourneyProvider to share data across components.


✍️ Step 3: Create the Journey Form

src/components/JourneyForm.js

import React, { useState, useContext } from 'react'; import { JourneyContext } from '../JourneyContext'; const JourneyForm = () => { const { addJourney } = useContext(JourneyContext); const [source, setSource] = useState(''); const [destination, setDestination] = useState(''); const [date, setDate] = useState(''); const handleSubmit = (e) => { e.preventDefault(); if (source && destination && date) { addJourney({ source, destination, date }); setSource(''); setDestination(''); setDate(''); } }; return ( <form onSubmit={handleSubmit} className="journey-form"> <input type="text" placeholder="From" value={source} onChange={(e) => setSource(e.target.value)} /> <input type="text" placeholder="To" value={destination} onChange={(e) => setDestination(e.target.value)} /> <input type="date" value={date} onChange={(e) => setDate(e.target.value)} /> <button type="submit">Add Journey</button> </form> ); }; export default JourneyForm;

This component lets users add new train journeys to the shared state.


📋 Step 4: Display the Journeys List

src/components/JourneyList.js

import React, { useContext } from 'react'; import { JourneyContext } from '../JourneyContext'; const JourneyList = () => { const { journeys, removeJourney } = useContext(JourneyContext); return ( <div className="journey-list"> <h2>My Planned Journeys</h2> {journeys.length === 0 ? ( <p>No journeys planned yet!</p> ) : ( <ul> {journeys.map((journey, index) => ( <li key={index}> <strong>{journey.source}</strong> → <strong>{journey.destination}</strong> on {journey.date} <button onClick={() => removeJourney(index)}>❌</button> </li> ))} </ul> )} </div> ); }; export default JourneyList;

This shows all journeys added by the user. Thanks to React Context, every time a new journey is added or removed, all components update automatically.


🎨 Styling the App (Optional)

src/App.css

.App { font-family: 'Segoe UI', sans-serif; max-width: 600px; margin: 30px auto; text-align: center; } .journey-form input, .journey-form button { padding: 8px; margin: 5px; } .journey-list ul { list-style: none; padding: 0; } button { background-color: #2196f3; color: white; border: none; cursor: pointer; border-radius: 4px; } button:hover { background-color: #1769aa; }

⚡ How React Hooks and Context Make State Management Easy

In traditional React apps, passing state between components often led to prop drilling, where data had to be passed through multiple nested levels.

With React Hooks like useState and Context API, we can:

  • Keep state localized using useState.

  • Share that state across multiple components using useContext.

  • Update UI instantly when state changes.

This makes your front-end cleaner, modular, and easier to maintain — perfect for apps like planners, to-do lists, or dashboards.


⚖️ React vs Angular vs Vue.js — Which is Better?

FrameworkTypeKey StrengthsLearning Curve
React.jsLibraryLightweight, reusable components, fast rendering via Virtual DOMModerate
AngularFrameworkFull-featured with routing, forms, and servicesSteeper
Vue.jsFrameworkSimplicity and reactivity, great for small-to-medium projectsEasy

React stands out for its ecosystem, developer community, and integration flexibility. If you want highly interactive UIs with minimal setup, React is a top choice for modern web apps.


🏁 Conclusion

We’ve just built a React-based Local Train Journey Planner App that demonstrates:

  • React Hooks for state management

  • React Context for sharing data between components

  • A clean, modular structure for building scalable front-end apps

Whether you’re planning your daily train commute or weekend city trips, this example showcases how React.js can be used to create fast, interactive, and stateful front-end applications.

If you’re learning React or building your next front-end project, this app is a great foundation to extend — for instance, by adding API integration, local storage, or even a map-based train route viewer!

Comments

Popular posts from this blog

Upload to AWS S3 from Java API

In this post, you will see code samples for how to upload a file to AWS S3 bucket from a Java Spring Boot app. The code you will see here is from one of my open-source repositories on Github, called document-sharing. Problem Let’s say you are building a document sharing app where you allow your users to upload the file to a public cloud solution. Now, let’s say you are building the API for your app with Spring Boot and you are using AWS S3 as your public cloud solution. How would you do that? This blog post contains the code that can help you achieve that. Read more below,  Upload to AWS S3 bucket from Java Spring Boot app - My Day To-Do (mydaytodo.com)

Build a Full-Stack Image Upload App with Node.js, Express, React, and Vite (Beginner Tutorial)

 If you’re new to full-stack web development and want a hands-on project to practice React frontend integration with a Node.js + Express backend , this tutorial is for you. In this guide, we’ll walk through a simple but powerful app that lets users upload images, store them on the server, and display them back in the browser. This project is based on my GitHub repo: node-express-react-simple-fileupload . It’s designed to be beginner-friendly, SEO-optimized, and a great starting point for anyone learning JavaScript full-stack development . 🛠️ Technologies Used Here’s the tech stack powering this project: Node.js – JavaScript runtime for the backend. Express.js – Lightweight web framework for building REST APIs. Multer – Middleware for handling file uploads. CORS – Enables cross-origin requests between frontend and backend. React.js – Frontend library for building user interfaces. Vite – Fast development server and build tool for React. Fetch API – For making HTTP requests ...

Html5 based widget for an iOS app: Today extension powered by the Ionic framework

At some point the thought of adding a Widget to my iOS app came to mind which was followed by starting work on adding a widget for my app, My Day Todos . Obviously the first step was to learn how to add a Widget to an iOS app and in that learning process I discovered many things about widgets in iOS first of which was a widget in iOS is a an app extension i.e a  Today Extension . While I am still haven't finished working on the widget for my iOS app, I thought I would take some time out and share what I have learned. In this post, I will share a few important tips and provide an example of how to add a Widget to an iOS app and have the widget UI powered by Html5 via  Ionic framework . I added some code to my Github repo, Html5StarterAppWithSwift in order to show how this can be achieved. There are already too many tutorials out on the Web on how to add a Today extension to an iOS app so I won't be including that here. Instead I will focus on sharing some of the useful tip...