#Do I need to subscribe in every component?

1 messages · Page 1 of 1 (latest)

gilded oar
#

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!

floral fjord
#

No you do not, and you're right, there is a better way!

#
const { durakService } = useContext(GlobalStateContext);
const deck = useSelector(durakService, state => state.context.deck);
gilded oar
#

@floral fjord thank you, I'll look up the details in the docs but that works!

It sounds like useSelector will always grab the latest value in context based on the latest state

floral fjord
#

Makes it much easier to create globally shared state

gilded oar
#

I have not but I'll definitely take a look. thanks again

gilded oar
#

this works but there are "weird" reloading issues when I save. Is that expected? I created and exported SomeMachineContext from inside my main.jsx file so that might be the issue

floral fjord
#

What are the reloading issues?

gilded oar
#

If I reload normally, none. But if I "save" and Vite reloads for me: ```Warning: You are calling ReactDOMClient.createRoot() on a container that has already been passed to createRoot() before. Instead, call root.render() on the existing root instead if you want to update it.

floral fjord
#

That's strange; under the hood, createActorContext is just using normal React context, the same way you would have done it (but abstracted in a function)