0Pricing
Micro Frontends Architecture with Module Federation · درس

إدارة الحالة المشتركة

استكشف استراتيجيات إدارة الحالة المشتركة عبر التطبيقات federated، مثل Redux أو Context API

إدارة الحالة المشتركة درس مجاني في Micro Frontends Architecture with Module Federation على CoddyKit. هذا هو الدرس 2 من أصل 4. يمكنك قراءة الدرس كاملاً أدناه مجاناً — ثم تمرن عليه مباشرة في المتصفح باستخدام محرر أكواد مدمج ومدرس ذكاء اصطناعي متاح 24/7. هذا الدرس جزء من مسار التعلم في Micro Frontends Architecture with Module Federation، وتقدمك يتزامن عبر الويب وتطبيق CoddyKit. تتضمن دورة Micro Frontends Architecture with Module Federation 4 دروس في المجموع.

بعض أجزاء هذا الدرس لم تُترجم بعد وتظهر باللغة الإنجليزية.

What is Shared State?

In Micro Frontends, shared state refers to data that needs to be accessible and consistent across different, independently developed and deployed applications.

  • Think of user authentication status, global theme settings, or shopping cart contents.
  • This state isn't owned by a single micro frontend but is crucial for a cohesive user experience.

Managing this state effectively is key to building complex federated applications.

Why Shared State in MFEs?

When you have multiple micro frontends making up a single user interface, they often need to react to the same global information.

  • User Experience: A user logs in on one MFE, and others need to know they're authenticated.
  • Consistency: Applying a global theme preference across all parts of the application.
  • Data Flow: Passing data from one MFE (e.g., product selection) to another (e.g., checkout).

Without shared state, each MFE would manage its own isolated data, leading to inconsistencies and a disjointed user journey.

Challenges of Shared State

While essential, sharing state in a Micro Frontend architecture comes with unique challenges:

  • Isolation: MFEs are designed to be independent. Breaking this isolation needs careful planning.
  • Framework Agnosticism: Different MFEs might use different JavaScript frameworks (React, Angular, Vue).
  • Performance: Inefficient sharing can lead to redundant data fetching or slow updates.
  • Complexity: Deciding ownership, update mechanisms, and preventing conflicts can be complex.

We need strategies that balance independence with the necessity of shared information.

Simple Shared State: Local Storage

For very basic, non-sensitive, and persistent state, browser's Local Storage can be a quick solution. Each MFE can read from and write to it.

However, it's not reactive, meaning MFEs don't automatically update when Local Storage changes. It's also not suitable for complex or real-time state.

Try setting and getting an item:

localStorage.setItem('appTheme', 'dark');
console.log('Theme set to dark.');

const currentTheme = localStorage.getItem('appTheme');
console.log('Current theme:', currentTheme);

// To remove:
// localStorage.removeItem('appTheme');
// console.log('Theme removed.');

Centralized State Stores

For more complex and reactive shared state, a centralized state store is a common pattern. Libraries like Redux are popular examples.

  • A single source of truth for your application's state.
  • Predictable state changes through actions and reducers.
  • Easier debugging and traceability of state modifications.

In a federated setup, a host or a dedicated remote MFE can expose such a store for others to consume.

Building a Simple Global Store

Let's create a basic, framework-agnostic global store. This store will hold our shared state and allow components to subscribe to changes. This mimics how a Redux store would function at a high level.

Run this code to see a simple store in action:

let sharedState = { userStatus: 'loggedOut', notifications: [] };
const subscribers = [];

function getSharedState() {
  return sharedState;
}

function dispatchAction(action) {
  switch (action.type) {
    case 'LOGIN':
      sharedState = { ...sharedState, userStatus: 'loggedIn' };
      break;
    case 'ADD_NOTIFICATION':
      sharedState = { ...sharedState, notifications: [...sharedState.notifications, action.payload] };
      break;
    default:
      return;
  }
  subscribers.forEach(cb => cb(sharedState));
}

function subscribe(callback) {
  subscribers.push(callback);
  return () => {
    const index = subscribers.indexOf(callback);
    if (index > -1) subscribers.splice(index, 1);
  };
}

// --- Example Usage ---
console.log('Initial state:', getSharedState());
const unsubscribe = subscribe(newState => {
  console.log('State updated:', newState);
});

dispatchAction({ type: 'LOGIN' });
dispatchAction({ type: 'ADD_NOTIFICATION', payload: 'Welcome!' });

unsubscribe();
console.log('Unsubscribed from updates.');

Consuming the Global Store

Now, imagine different Micro Frontends needing to react to changes in this global store. They would use the getSharedState and subscribe functions.

This example demonstrates how two 'virtual' MFEs could interact with the shared store, reacting to updates.

let sharedState = { userStatus: 'loggedOut', notifications: [] };
const subscribers = [];

function getSharedState() { return sharedState; }
function dispatchAction(action) {
  switch (action.type) {
    case 'LOGIN': sharedState = { ...sharedState, userStatus: 'loggedIn' }; break;
    case 'ADD_NOTIFICATION': sharedState = { ...sharedState, notifications: [...sharedState.notifications, action.payload] }; break;
    case 'LOGOUT': sharedState = { ...sharedState, userStatus: 'loggedOut' }; break;
    default: return;
  }
  subscribers.forEach(cb => cb(sharedState));
}
function subscribe(callback) {
  subscribers.push(callback);
  return () => { const index = subscribers.indexOf(callback); if (index > -1) subscribers.splice(index, 1); };
}

// --- MFE A (e.g., Header Component) ---
function handleUserStatusChange(state) {
  console.log('MFE A: User status is now', state.userStatus);
}
const unsubscribeMFEA = subscribe(handleUserStatusChange);

// --- MFE B (e.g., Notification Bell) ---
function handleNotificationsChange(state) {
  console.log('MFE B: Notifications:', state.notifications.length);
}
const unsubscribeMFEB = subscribe(handleNotificationsChange);

// Simulate actions from other MFEs or host
dispatchAction({ type: 'LOGIN' });
dispatchAction({ type: 'ADD_NOTIFICATION', payload: 'New message!' });
dispatchAction({ type: 'LOGOUT' });

unsubscribeMFEA();
unsubscribeMFEB();

React Context API for MFEs

If your Micro Frontends are all built with React, the Context API can be a powerful way to share state. A Context provides a way to pass data through the component tree without having to pass props down manually at every level.

  • Create a Context in a shared library or a host MFE.
  • Expose this Context via Module Federation.
  • Remote MFEs can then consume this Context directly.

This approach works well when all federated applications are within the same React ecosystem.

Sharing React Context (Concept)

To share React Context, you'd typically:

  1. Define Context: Create MyContext.js in a shared utility MFE.
  2. Expose Context: Use Module Federation to expose MyContext.Provider and useContext(MyContext).
  3. Provide Context: The host MFE (or a parent MFE) wraps its children (including remote MFEs) with the <MyContext.Provider value={...}>.
  4. Consume Context: Any remote MFE can then import and use useContext(MyContext) to access the shared state.

This allows a deeply nested component in a remote MFE to access state provided by a parent MFE.

Question: Shared State Benefits

You've learned about various approaches to managing shared state in Micro Frontends.

Which of the following is a primary benefit of implementing robust shared state management in a Micro Frontend architecture?

Recap: Shared State Management

We've explored key strategies for managing shared state in Micro Frontends:

  • Need: Essential for consistent user experience and data flow across independent MFEs.
  • Challenges: Maintaining isolation, framework compatibility, and managing complexity.
  • Simple Methods: Local Storage for basic, non-reactive data.
  • Centralized Stores: Using patterns like Redux to create a single source of truth, accessible by all MFEs.
  • React Context: An effective solution for sharing state when all MFEs are within the React ecosystem.

Choosing the right strategy depends on your team's needs, framework choices, and the complexity of the shared data.

الأسئلة الشائعة

هل درس «إدارة الحالة المشتركة» مجاني؟

نعم — نص درس «إدارة الحالة المشتركة» كامل متاح مجاناً هنا على الويب. لتمرينه بشكل تفاعلي (محرر أكواد مدمج ومدرس ذكاء اصطناعي متاح 24/7) وفتح باقي دورة Micro Frontends Architecture with Module Federation، انتقل إلى CoddyKit PRO. تتضمن دورة Micro Frontends Architecture with Module Federation 4 دروس في المجموع.

ماذا ستتعلم في «إدارة الحالة المشتركة»؟

استكشف استراتيجيات إدارة الحالة المشتركة عبر التطبيقات federated، مثل Redux أو Context API تتمرن على Micro Frontends Architecture with Module Federation مع أكواد عملية تشغلها مباشرة في المتصفح، ومدرس ذكاء اصطناعي متاح 24/7 يجيب على أسئلتك أثناء عملك.

هل أحتاج إلى خبرة سابقة لأبدأ Micro Frontends Architecture with Module Federation؟

لا تُشترط خبرة سابقة. Micro Frontends Architecture with Module Federation على CoddyKit منظم للمبتدئين حتى المتقدمين، لذا يمكنك البدء من هنا أو من البداية والتقدم بسرعتك الخاصة. هذا هو الدرس 2 من أصل 4.

كم من الوقت يستغرق درس «إدارة الحالة المشتركة»؟

معظم دروس CoddyKit تستغرق حوالي 5–10 دقائق. كل منها موجز وتفاعلي، لذا تحرز تقدماً مستمراً وتستأنف من حيث توقفت عبر الويب والتطبيق.

هل يمكنني كتابة وتشغيل أكواد في درس Micro Frontends Architecture with Module Federation هذا؟

نعم. كل درس في Micro Frontends Architecture with Module Federation يتضمن محرر أكواد مدمج، لذا تكتب وتشغل أكواداً حقيقية مباشرة في متصفحك وتحصل على تعليقات فورية من الذكاء الاصطناعي — بدون إعداد محلي.

جميع الدروس في هذه الدورة

  1. حافلة الأحداث للتواصل بين التطبيقات
  2. إدارة الحالة المشتركة
  3. حلول التواصل المخصّصة
  4. التواصل باستخدام أحداث DOM المخصصة
← العودة إلى Micro Frontends Architecture with Module Federation