'Access context outside render tree
I have an app in React Native that uses many context. I want to access one of them within a non rendering function e.g. :
const DataContext = React.createContext();
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
// ...
systemState: {},
// ...
};
}
componentDidMount() {
const systemState = offlineSystemState();
this.setState(systemState);
}
// ...
render() {
return (
<DataContext.Provider value={this.state}>
<CustomComponent />
</DataContext.Provider>
);
}
}
// OfflineSystemState component wants access to the DataContext,
// but impossible because it is not being rendered.
// Error: Invalid hook call. Hooks can only be called inside of the body of a function component.
const offlineSystemState = () => {
const context = useContext(DataContext);
const systemState = processData(context.data);
return systemState;
};
Is it possible to do this ? If not, is there a store that can do it (Redux, Mobx, ...) ?
Thanks.
Solution 1:[1]
After more than one year searching for a solution, my conclusion is that it is simply not possible.
Only solution is to pass dependencies directly to the non rendering service and the context to share one dependency instance.
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 | BenjaminB |