Say I have something like this:
import React, { createContext, useState, useContext, ReactNode } from 'react';
interface ChannelProviderProps {
children: ReactNode;
}
const ChannelContext = createContext<{ channelId: string, setChannelId: React.Dispatch<React.SetStateAction<string>> } | null>(null);
export const ChannelProvider = ({ children }: ChannelProviderProps) => {
const [channelId, setChannelId] = useState<string>('Initial');
return (
<ChannelContext.Provider value={{ channelId, setChannelId }}>
{children}
</ChannelContext.Provider>
);
};
export const useChannel = () => {
const context = useContext(ChannelContext);
console.log('useChannel context is: ', context);
if (!context) {
const errorMessage = `Existing context not found.n useChannel must be used within a ChannelProvider`
throw new Error(errorMessage);
}
return context;
};
And I have Component A, and Component B… both of which have this provider wrapped around them:
<ChannelProvider>
<Component A />
</ChannelProvider>
<ChannelProvider>
<Component B />
</ChannelProvider>
If Component A has this code:
const { channelId, setChannelId } = useChannel();
useEffect(() => {
setChannelId('SomethingElse')
}, []);
and Component B has this code:
const { channelId, setChannelId } = useChannel();
useEffect(() => {
console.log(channelId);
}, [channelId]);
If both components are mounted, will Component B print out ‘Initial’, or will it print ‘SomethingElse’?
I’m not sure if I’m grasping this exactly. I can appreciate and understand when dependency arrays rely on the component’s local states… but I’m unsure of ‘remote’ states.
Would Component B need to re-render in order to have awareness of this newly updated channelId?
1
In your setup, Component A
and Component B
are each wrapped in their own ChannelProvider
. This means:
- Each
ChannelProvider
has its own separatechannelId
state. Component A
updates its ownchannelId
to'SomethingElse'
.Component B
has a differentChannelProvider
and retains itschannelId
as'Initial'
.
Therefore, when Component B
logs channelId
, it will print ‘Initial’ because the two components do not share the same state.
1