'React Context accessing current state out of component

I am trying to make an react application and I am newer to hooks and new context API, I use redux in my projects normally but I wanted to try context API and hooks in this project but I am struggling with some concepts of context API. only thing I need is a getState function like redux has I tried using reducers;

import MainContext from '../contexts/mainContext';

const initialState = {
localMember:null,
remoteMember:null,
signedIn:false,
videoPermission: true,
audioPermission: true,
selectedGender:0,
connecting:false,
};    

const reducer = (state,action) => {
switch(action.type) {
    case constants.SET_STATE:{
        console.log(action.payload);
        return {...state,...action.payload}
    }
    case constants.UPDATE_LOCAL_MEMBER:{
        return {...state, localMember:{...state.localMember,...action.payload} }
    }
    default:
        return state;
}
}; 

const ProviderComponent = () => {

const [state,dispatch] = React.useReducer(reducer,initialState);

const value = {
    dispatch:dispatch,
    getState:() => state
};
Provider Component

<MainContext.Provider value={value}>
        {children}
</MainContext.Provider>
}

const SubComponent = () => {

const {getState,dispatch} = useContext(MainContext);

useEffect( ()=> {
    SocketClient.install({getState,dispatch});
},  [init]);

return <div>component<div>;
}

and useContext hook to get the current state and getState function and passed that function as an argument to a Class when component mount by useEffect hook and stored that function in that class and tried to acces to state by calling it but I dont current state , state is always same and initial one how can I achive something that we do with getState function of redux store



Solution 1:[1]

You can only use hooks inside a react component. but if you have to call some Actions from outside of your component you can inject it into you window and use everywhere you want like interceptors or something else...

if (typeof window !== 'undefined') 
        window['logoutDispatch'] = () =>
            Actions.logOutUser()(dispatch)

then you can simply call this action everywhere and it's will update you state in context and re render your application.

window.logoutDispatch() 
//or
logoutDispatch()

if you using nextJs or any SSR just be sure to call this in client side with checking window is available or not.

const logoutDispatch = () =>
typeof window !== 'undefined' && window?.['logoutDispatch']()

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 mahdi ashori