In Memory Data Saving
In a React application, in-memory data saving refers to temporarily storing data in the memory (RAM) during the app's lifecycle. This data doesn't persist after the app reloads or the user leaves the page, unlike data stored in local storage, session storage, or a database.
Use Case
In-memory data is ideal for managing temporary states like:
- User authentication status (e.g., logged-in user details)
- UI state (e.g., theme, language preference)
- Temporary form data or shopping cart items
Why Use Context API?
React's Context API provides a way to share state across components without passing props down manually at every level. It’s commonly used to manage global state like in-memory data.
Steps to Save and Use In-Memory Data with Context API
-
Create a Context
A context acts as a central store for the data. -
Provide the Context
Wrap your app (or part of it) with aProvider
to share the data. -
Consume the Context
Access the context data in any child component usinguseContext
.
Implementation Example: User Authentication
Step 1: Create the Context
import React, { createContext, useState } from "react";
// Create a Context
export const AuthContext = createContext();
// Create a Provider component
export const AuthProvider = ({ children }) => {
const [user, setUser] = useState(null); // Store user data in memory
const login = (userData) => setUser(userData); // Function to log in
const logout = () => setUser(null); // Function to log out
return (
<AuthContext.Provider value={{ user, login, logout }}>
{children}
</AuthContext.Provider>
);
};
Step 2: Wrap Your App with the Provider
import React from "react";
import ReactDOM from "react-dom";
import App from "./App";
import { AuthProvider } from "./AuthContext";
ReactDOM.render(
<AuthProvider>
<App />
</AuthProvider>,
document.getElementById("root")
);
Step 3: Consume the Context
Use the useContext
hook in any child component to access or update the data.
import React, { useContext } from "react";
import { AuthContext } from "./AuthContext";
const Profile = () => {
const { user, login, logout } = useContext(AuthContext);
return (
<div>
{user ? (
<div>
<h2>Welcome, {user.name}!</h2>
<button onClick={logout}>Logout</button>
</div>
) : (
<button
onClick={() =>
login({ name: "Md. Mojnu Miah", email: "mojnu@example.com" })
}
>
Login
</button>
)}
</div>
);
};
export default Profile;
Key Points
- Data Storage: The
useState
hook inside the context stores the data in memory. - Data Sharing: The
AuthContext.Provider
shares data with its children. - Accessing Data: The
useContext
hook simplifies accessing the shared data.