#[Solved] MDX with React's useContext

4 messages · Page 1 of 1 (latest)

atomic kayak
#

Hello! Want to make sure whether I can use React's useContext inside mdx for sharing state or not. I only want to share it to one island so I don't think nanostore is necessary.

Here's what I'm trying to do:

import Component from "@/components/React/Component";
import { ContextProvider } from "@/components/React/Provider";

<ContextProvider client:load>
  <Components client:load /> // <- Component that need to access state
   <Components client:load />
</ContextProvider>

and the context code:

const Context = React.createContext({
  state: dummyState,
  dispatch: () => {
    console.log("dispatch not initialized");
  },
});

const ContextProvider = ({ children }) => {
  const [state, dispatch] = React.useReducer(Reducer, dummyState);


  return (
    <Context.Provider value={{ state, dispatch }}>
      {children}
    </Context.Provider>
  );
};

The problem I'm facing is that the dispatch function and possibly the state is not initialized as I kept getting "dispatch not initialized" whenever I called dispatch. Is it possible to make it work or do I have to use nanostore for this?

stone ingot
#

For something like that do you really need context/state?

Could you just make a wrapper for both components that handles the state and passes it down as props?

atomic kayak
#

I try to make context work because I'm planning to add interactivity between the children components. Making a wrapper does work. It seems that creating two different components will make 2 instead of 1 single island.

stone ingot
#

Sorry just to clarify that solution will or will not work for you?

If it does feel free to tag this as solved and close it, if not we can dig deeper