Why does spliting context to a separate file double the result?

34 Views Asked by At

Below are two versions of my code. When the context is not split into a separate file, the result is only christy, working as expected. However when it is split, then the result is doubleas christychristy. I can't reasoning why this is the case. Do you have any idea?

Not splitting context to another file

routes/index.tsx

import { User } from "../islands/User.tsx";
import { createContext } from 'preact'

export const Form1Context = createContext()

export function Context2Provider({children}) {
  return (
    <Form1Context.Provider value="christy">{children} 
    </Form1Context.Provider>
  );
}

export default function App() {
  return (
    <Context2Provider>
      <User />
    </Context2Provider>
  )
}

islands/User.tsx

import { useContext } from 'preact/hooks';
import { Form1Context } from '../routes/index.tsx'

export function User() {
  const username = useContext(Form1Context); 
  return <>{username}</>;
}

The result of this is christy.

Splitting context to another file

routes/index.tsx

import Context2Provider from '../islands/Context.tsx'
import { User } from "../../fresh-project/islands/User.tsx";

export default function App() {
  return (
    <Context2Provider>
      <User />
    </Context2Provider>
  )
}

islands/Context.tsx

import { createContext } from 'preact'


export const Form1Context = createContext()

export default function Context2Provider({children}) {
  return (
    <Form1Context.Provider value="christy">{children} 
    </Form1Context.Provider>
  );
}

islands/User.tsx

import { useContext } from 'preact/hooks';
import { Form1Context } from './Context.tsx'

export function User() {
  const username = useContext(Form1Context);
  return <>{username}</>;
}

The result of this is christychristy.

0

There are 0 best solutions below