Skip to main content

SitecoreContext series

This blogpost is part of a short series on the SitecoreContext object


In the previous blogpost Sitecore JSS: Exploring the SitecoreContext Object I talked about the SitecoreContext object, what it is and what it offers. Let’s repeat what it is:

The SitecoreContext object provides context-aware data to components within your Sitecore JSS app, and can for example be useful when you need to modify the behavior of the JSS app/website based on the current context. The SitecoreContext object contains data about the current request and the Sitecore environment and is populated by the Sitecore Layout Service.

In that blogpost I mentioned that there are various ways of accessing it. In this blogpost I’ll explore the first one, which is the ‘useSitecoreContext’ hook.

Let’s first explore what hooks are in React. React hooks were introduced in React 16.8 that allowed functional components to have state and other features previously only available to class-based components. Before React hooks, developers would have to write a class to create a component that had state or used other React features, such as lifecycle methods.

The ‘useSitecoreContext’ hook is a React hook provided by the @sitecore-jss/sitecore-jss-nextjs package that allows a Sitecore JSS Next.js component to access the Sitecore context. To use the ‘useSitecoreContext’ hook, you must first import it from the @sitecore-jss/sitecore-jss-nextjs package.

Then, you can call the hook within the body of a functional component, and it will return an object containing the Sitecore context. To include the output of various Sitecore context properties in a component, you can then access the properties on the Sitecore context object returned by the ‘useSitecoreContext’ hook and render them as part of the component. Here is an example of how you might do this:

In this example, I access the ‘itemId’, ‘language’, and ‘site.name’ properties on the SitecoreContext object and render them as a list within the default ‘ContentBlock’ component (that you get out of the box when you create a new Sitecore JSS/Next.js app). This allows us to see the output of these properties when the ‘ContentBlock’ component is rendered.

Sitecore JSS: Exploring the useSitecoreContext Hook example

And that’s it! As you can see it’s very easy with the ‘useSitecoreContext’ hook to access Sitecore context data. What happens a lot for example in projects is checking the ‘pageEditing’ prop from the SitecoreContext object, for example to render additional information to a component when you’re page editing in the Experience Editor, something you don’t want to display on a live website.

In the next blog post I’ll be exploring a different way of getting access to the SitecoreContext object.

Happy Sitecoring!

–Robbert