Short answer: It's not safe in production, instead you can maintain a global variable.
This "hack" is exactly like reading from a global variable. Your component can't be notified when the global variable updates.
See the explanation on global variables here: Why need useRef to contain mutable variable but not define a variable outside the component function?
let counter = 0;
const Component = () => {
/*
On changing the counter value, the component won't get re-rendered with its new value.
*/
console.log(counter);
return <></>
}
Is there a solution for React hooks to just read current state without subscription like Redux's store.getState()
?
store.getState()
returns the last value returned by the store's reducer. It's exactly the behavior like you intended with UsersStateContext._currentValue
, if you want to feel safer, you can maintain a global variable as mentioned.
The official way is to subscribe to context by consuming it, for example with useContext
:
const value = useContext(MyContext);