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)

Addressing app review rejections for auto-renewing subscription in-app purchase (iOS)

The ability to know what the weather is like while planning your day is a feature of  My Day To-Do  Pro and as of the last update it’s also a part of the  Lite version . Unlike the Pro version it’s an auto-renewing subscription based  in-app purchase (IAP)  in the Lite version. What means is that when a user purchases it, the user only pays for the subscription duration after which the user will be automatically charged for the next period. Adding an  auto-renewing  subscription based IAP proved to be somewhat challenging in terms of the app store review i.e. the app update was rejected by the App Review team thrice because of missing information about the IAP. Therefore in this post I will share my experiences and knowledge of adding auto-renewing IAP in hopes to save someone else the time that I had to spend on this problem. In-App purchase This year I started adding IAPs to My Day To-Do Lite which lead to learning about different types of IAP...

Serving HTML content in an iOS app that works in iOS 7 and later (using Swift)

As I have mentioned in an earlier post , I really enjoying coding in Swift. Now what am I doing with it? Well I am trying to build an HTML5 app that must work on devices with iOS 7. So in iOS8 apple has introduced a whole bunch of features that facilitate easy communication between web content and lets just call it back-end Swift code, but those features are not in iOS 7. So why do I want to build something that would work in an older OS? well I do not expect existing iOS users to upgrade to iOS 8 straight away and i also know a couple of people who would be very reluctant to upgrade their iPhones to iOS 8. Now in case you do not, you can have a read of the "Working with WebViews" section of this post , to know how to serve HTML content with WebViews. So when I started building my app, I wanted to know: How do I invoke some Swift code from my HTML content? Well the solution to this may feel a little bit "hacky" but it is a solution to achieve this.  The followi...