Don't pass the whole web part context into your React components


Passing the whole web part context into React components might seem convenient at first, but is far from it in the long run.

Convenience, but really?

You see it everywhere. Someone built a web part or extension on the SharePoint Framework using React. The React component needs to retrieve some data, and so the developers follow the recommendation to use the SharePoint Framework HTTP clients. But to use them inside React components, they pass the whole web part context to the component using its properties.

Code of a SharePoint Framework web part built using React in Visual Studio Code
Passing the whole web part context into React components - bad idea

Here is why it’s a bad idea.

Why passing the whole web part context to React components is a bad idea

If you’re passing the whole web part context into your React components, you’re probably not building unit- or integration tests for them. The moment you build your first test for your React component, you will immediately understand why passing the whole web part context through component’s properties is a bad idea.

Here is how the web part context object looks like:

Partial list of properties of the web part context object displayed in Visual Studio Code
That's a lot of properties

There are even more properties than fit in the intellisense box and what’s even worse, is that majority of them are complex objects with their own properties. So if you were to write a unit test and had to create a mock object for the context, you would need to spend quite some to build the mock without making any assumptions about the underlying code.

The good news is, that probably you don’t need the whole web part context in your React component.

What you should do instead of passing the whole web part context to React components

When building SharePoint Framework solutions you will likely need a few context properties, like the HTTP clients or the URL of the current site, but not all of them. So instead of passing the whole context to your React components, you should pass only what you need. It might seem more work at first, especially if you don’t have the whole design thought out and things are still in flux. But in the end you will appreciate it. Not only your code will be cleaner but you will also be able to test it more easily. Be lazy but also be clever, in the long run.

Others found also helpful: