I am passing a function to as value to the Context Provider
and on calling that function from the consumer, I'm getting the older state.
Provider.jsx
const MyContext = createContext();
const Provider=()=>{
const [someState, setSomeState] = useState();
const providerFunction=()=>{
// accessing someState
}
<MyContext.Provider value={{providerFunction}}>
<ConsumerComponent/>
</MyContext.Provider>
Comsumer.jsx
const {providerFunction} = useContext(MyContext);
On calling providerFunction
from Consumer.jsx
, providerFunction in Provider.jsx is called but someState
is not getting the updated value, it is printing the initial value assigned to it.
I'm unable to figure out the reason for this. Any help is appreciated.
I figured out the issue, actually, I was using debounce
in Consumer
and in useCallback
, I missed passing providerFunction
as a dependency.
After adding the dependency, it worked!
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.