I'm using a GlobalStateProvider with a useInterpret() service that I pass in as the value. Do I need to subscribe to the service in every component? It seems like there should be a better way.
Here's an example component that I am using to grab context values from my machine:
import { GlobalStateContext } from "../providers/GlobalStateProvider";
export default function Deck() {
const { durakService } = useContext(GlobalStateContext);
const [deck, useDeck] = useState([]);
useEffect(() => {
const subscription = durakService.subscribe((newState) => {
useDeck(newState.context.deck);
});
return () => {
subscription.unsubscribe();
};
}, [durakService]);
return (
<div>
<p>Deck:</p>
{deck.length &&
deck.map((card, index) => (
<div key={index}>{JSON.stringify(card)}</div>
))}
</div>
);
}
I could also use:
export default function Deck() {
const { durakService } = useContext(GlobalStateContext);
const { deck } = durakService.state.context;
return (
<div>
<p>Deck:</p>
{deck.map((card, index) => (
<div key={index}>{JSON.stringify(card)}</div>
))}
</div>
);
}
Is there a benefit to either approach?
Do I have to subscibe to always have the latest value or will re-rendering handle that?
Any insight would be much appreciated!