This reusable Higher Order Component handles asynchronous data fetching in React applications, making it ideal for fetching data from APIs on componen...
Back to Snippets
javascript
• 88 lines
JavaScript
PHP
PHP
React Context API Pattern For Managing Global State In Large-Scale Applications
This React code snippet demonstrates a centralized global state management pattern using the Context API, simplifying state access and updates across components. It is particularly useful in large-scale applications where global state needs to be accessed and updated frequently, and includes error handling and input validation for production use. The code provides a robust solution for managing global state, reducing complexity and improving code organization. To use this snippet, you should have a basic understanding of React and its Context API.
Snippet Stats
Lines
88
Characters
1,955
Read
3 mins
import React, { createContext, useState, useEffect, useContext } from 'react';
const GlobalStateContext = createContext();
const API_URL = process.env.REACT_APP_API_URL;
const GlobalStateProvider = ({ children }) => {
const [user, setUser] = useState(null);
const [loading, setLoading] = useState(true);
const [error, setError] = useState(null);
useEffect(() => {
let isMounted = true;
const fetchUserData = async () => {
try {
const response = await fetch(API_URL, {
mode: 'cors',
headers: {
'Content-Type': 'application/json'
}
});
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const data = await response.json();
if (isMounted) {
setUser(data);
setLoading(false);
}
} catch (error) {
if (isMounted) {
setError(error);
setLoading(false);
}
console.error('Error fetching user data:', error);
}
};
fetchUserData();
return () => {
isMounted = false;
};
}, []);
const updateUser = (newUser) => {
if (newUser && typeof newUser === 'object') {
setUser(newUser);
} else {
console.error('Invalid user data:', newUser);
}
};
return (
<GlobalStateContext.Provider value={{ user, loading, error, updateUser }}>
{children}
</GlobalStateContext.Provider>
);
};
const useGlobalState = () => {
const context = React.useContext(GlobalStateContext);
if (!context) {
throw new Error('GlobalStateContext is not provided');
}
return context;
};
const ExampleComponent = () => {
const { user, loading, error } = useGlobalState();
if (loading) {
return <div>Loading...</div>;
}
if (error) {
return <div>Error: {error.message}</div>;
}
if (!user || !user.name) {
return <div>Hello, Guest!</div>;
}
if (typeof user.name !== 'string') {
console.error('Invalid user name:', user.name);
return <div>Hello, Guest!</div>;
}
return <div>Hello, {user.name}!</div>;
};
Found an issue with this snippet? Help us improve by reporting it. Report it →
Related Snippets
View allThis code snippet provides a custom WordPress hook to update user profiles. It is useful when you need to synchronize user data with external services...
Add custom sortable admin columns to any post type — render post meta in the admin list table with proper escaping.