When using MobX, we typically employ the observer function within React components to monitor state changes and trigger re-renders. For stateless components (stateless functional components), we can still access and inject the store using React's useContext hook or higher-order components (HOC). Below are two common approaches:
Method 1: Using the useContext Hook
If your store is provided via React's Context API, you can access the MobX store in a stateless component using the useContext hook. First, ensure your store is wrapped in a Context and provided through a Provider at some level within the application.
jsximport React, { useContext } from 'react'; import { observer } from 'mobx-react'; import { StoreContext } from './StoreProvider'; // Assuming your store is provided this way const MyComponent = observer(() => { const store = useContext(StoreContext); // Use useContext to retrieve the store return <div>{store.someValue}</div>; }); export default MyComponent;
In this example, StoreContext is a Context object used to pass the MobX store via React's Context API. MyComponent is an observer component that responds to changes in the store.
Method 2: Using Higher-Order Components (HOC)
Another approach involves creating a higher-order component that encapsulates the observer and references the store. This method was more prevalent in earlier React versions, particularly before Hooks were introduced.
jsximport React from 'react'; import { observer, inject } from 'mobx-react'; const withStore = (Component) => inject('store')(observer(Component)); const MyComponent = ({ store }) => ( <div>{store.someValue}</div> ); export default withStore(MyComponent);
Here, withStore is a higher-order component that injects the store from the context and transforms MyComponent into an observer. Consequently, MyComponent can access the injected store and react to its changes.
Summary
Using useContext offers a more modern and concise way to inject the MobX store into function components, while the HOC method suits older projects or codebases that haven't adopted Hooks. In practice, it's advisable to select the appropriate method based on your project's specific context and team preferences.