Skip to content

One shared instance between multiple React components #1754

Answered by davidkpiano
miloslavnosek asked this question in Q&A
Discussion options

You must be logged in to vote

I'm currently writing an article on this, but I'd recommend doing it through context:

const ServiceContext = React.createContext();

const App = ({ children }) => {
  const [_state, _send, service] = useMachine(someMachine);

  return (
    <ServiceContext.Provider value={service}>
      {children}
    </ServiceContext.Provider>
  );
}

// in a child...
const Child = () => {
  const service = React.useContext(ServiceContext);
  const [state, send] = useService(service);

  // ...
}

The pattern above feels pretty natural and idiomatic to React.

Replies: 5 comments 19 replies

Comment options

You must be logged in to vote
1 reply
@miloslavnosek
Comment options

Comment options

You must be logged in to vote
9 replies
@siman
Comment options

@davidkpiano
Comment options

@sebastienbarre
Comment options

@pke
Comment options

@redbar0n
Comment options

Answer selected by miloslavnosek
Comment options

You must be logged in to vote
3 replies
@Andarist
Comment options

@redbar0n
Comment options

@mattpocock
Comment options

Comment options

You must be logged in to vote
6 replies
@davidkpiano
Comment options

@with-heart
Comment options

@VILLAN3LL3
Comment options

@davidkpiano
Comment options

@VILLAN3LL3
Comment options

Comment options

You must be logged in to vote
0 replies
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet