How can i access the react context value inside normal Js function. Example I have a normal js function that is being used in many react components in my application. In that js function I need one of my react context value. So Currently I am passing that context value to that function as parameter from wherever it is being called. Is there any way to get that context inside that function instead of passing it from everywhere.
Context:
export const WidgetContext = React.createContext({});
export const useWidgetContext = () => useContext(WidgetContext);
Function:
export const utilsFn = (contextValue) => {
console.log(contextValue)
return contextValue;
}
Component 1:
import { useWidgetContext } from 'WidgetContext';
export default const Comp1 = () => {
const { contextValue } = useWidgetContext();
const utilsFn(contextValue)
return (
)
}
Component 2:
import { useWidgetContext } from 'WidgetContext';
export default const Comp2 = () => {
const { contextValue } = useWidgetContext();
const utilsFn(contextValue)
return (
)
}
In the above example, how can i access that context value inside that utilsFn without passing from all the components.
React useContext is a hook as mentioned in the docs. As you can see here react allows to use hooks inside of custom hooks.
However the response to
How can i access the react context value inside normal Js function
is that you can't and you shouldn't try (because react won't allow it, but if you want to dive deeper into this here is some related information and here are the Rules of Hooks)
But what you can do is create a custom hook for your util. Something like:
import { useWidgetContext } from 'WidgetContext';
export const useUtils = () => {
const { contextValue } = useWidgetContext();
console.log(contextValue)
return contextValue;
}
And as long as you don't break the Rules of Hooks it should work just fine