🚛 React Essentials: Passing Data Between Pages Made Simple! 🌟

🚛 React Essentials: Passing Data Between Pages Made Simple! 🌟

Working on a trucking app, I had to figure out the best ways to pass data like truckNumber and sealNumber between pages or components. It got me thinking: 🤔 What are the most effective methods for passing data in React?

Here’s a roundup of 7 powerful ways you can use depending on your needs:


1️⃣ Passing Data via Props

For parent-child communication, props are the go-to solution:

Example:

Article content

Use this when both components are tightly coupled in the same hierarchy.


2️⃣ React Router state

For navigation between pages, you can use the state property in React Router.

Step 1: Pass data with Link:

Article content

Step 2: Access data using useLocation:

Article content

Great for passing temporary data during navigation!


3️⃣ Context API

The Context API eliminates prop-drilling and is perfect for global/shared state.

Example:

Article content

Wrap your app with the TruckProvider to use this across components.


4️⃣ Local Storage / Session Storage

For persisting data across sessions or after a page reload:

Example:

  • Save data:

Article content

  • Retrieve data:

Article content

Great for caching lightweight data temporarily.


5️⃣ Redux (or State Management Libraries)

For complex state management across the app:

Example:

  • Dispatch an action:

Article content

  • Access state:

Article content

Use Redux when managing data at scale across multiple pages.


6️⃣ Query Parameters

For URL-driven, lightweight data sharing:

Example:

  • Pass data:

Article content

  • Access data:

Article content

This keeps the data visible in the URL for bookmarkable routes.


7️⃣ Custom Hooks

Encapsulate reusable logic into a custom hook:

Example:

Article content

Custom hooks make your code modular and reusable.


Which One Should You Use? 🤔

  • Props: Simple parent-to-child communication.
  • React Router state: Temporary data transfer between pages.
  • Context API: For global/shared app state.
  • Local Storage: Persist data across page reloads or sessions.
  • Redux: Manage complex app-wide state efficiently.
  • Query Parameters: URL-driven lightweight sharing.
  • Custom Hooks: Reusable, modular state-sharing logic.


✨ Each method has its place in the React ecosystem. Choosing the right one depends on your app’s complexity, data lifecycle, and state requirements.


To view or add a comment, sign in

More articles by Kajasumanie kanapathipillai

Explore content categories