Get the Sitecore context with React Hooks

When you are building a React app with Sitecore JSS there is a higher order component that can inject the Sitecore context.

This is the example from the official docs:

import { withSitecoreContext } from '@sitecore-jss/sitecore-jss-react';

const MyComponent = (props) => <div>Page editing: {props.sitecoreContext.pageEditing}</div>;

// wrap MyComponent in the HOC (note the double function invocation - important)
export default withSitecoreContext()(MyComponent);

Currently you can only get the Sitecore context by using the higher order component, but sometimes you don't want to use that. For example if you are creating your own Hook. I've submitted a PR which makes it possible to get the Sitecore context with a Hook:

import { useContext } from 'react';
import { SitecoreContextReactContext } from '@sitecore-jss/sitecore-jss-react';
const sitecoreContextFactory = useContext(SitecoreContextReactContext);
const pageEditing = sitecoreContextFactory.getSitecoreContext().pageEditing;

The PR is merged, but currently it's not released yet. So when the next version of Sitecore JSS is released you'll be able to use the above code sample. As mentioned in the related issue it might be better to create a custom Hook which exposes the Sitecore context, but for now at least you can get it.