Should React Context be used?

React Context is an API that allows components (regardless of the depth of the hierarchy) to provide information without explicitly passing information via props.

I wrote an article about sharing data globally before, but as I wrote more code in Next.js, I was wrong. I began to think.

Tsukurue
【Nextjs】useContextを使用して、アプリケーション全体でデータを共有する | Tsukurue useContextはReact Hookで提供されています。これを使うことであるコンポーネントから別のコンポーネントへデータを渡すことができます。ユーザーセッションなど、グローバ...
目次

What is React Context?

Normally, information from a parent component to a child component is passed via props. Context can then be used to share state to lower components without having to go through props. Passing props to subordinate components at the back is often redundant and inconvenient, and above all, it may go through components that do not use state at all, so Context is convenient and a good experience in this respect.

However, global state using Context is not always an appropriate option.

Issues when using React Context.

Components using Context and the associated React tree are always re-rendered when the state provided by the context changes. It does not matter whether the component is actually using the changed state part or not. This means that extra rendering can occur.

It is therefore undesirable to provide huge state in Context. It is advisable to reconsider the data to be held, and consider whether it is possible to replace it with hooks, etc.
With props, it is easy to know where the data is being referenced.

Which situations should it be used in?

It should be used in situations where the state does not change frequently and is not complex.
This is the case for themes, login status, language settings, etc.

Summary

If you use an inappropriate Context, you will feel the performance loss due to re-rendering like a body blow as you get bigger.
You want to keep in mind what kind of state management you want to do and what scope you want to use it for.

シェア!

この記事を書いた人

kenichiのアバター kenichi エンジニア・写真家 | Engineer and photographer

Nomadic worker who travels all over Japan and abroad; worked as a technical sales person for five years before going independent.
Works as a freelance engineer on website production and application development. Currently working to bring interesting things by interesting people to the world, while seeking to move abroad.

目次