最近有一些人問為什麼在開發React專案上,不會選擇使用Redux而是選擇使用Context在專案上?以下就來簡單說明一下可能的原因。

首先,當要討論為什麼是A而不是B這件問題的時候,我們應該回頭過來討論專案的需求是什麼?什麼因素會影響這些需求。

使用Context簡單又方便,特別是在剛開發的小專案上面使用很容易。

什麼是Context

讓我們先來看官方的介紹:
Context provides a way to pass data through the component tree without having to pass props down manually at every level.

短短的一句話,就介紹完什麼是Context了,簡單來說,React為了解決從parent component傳遞資料到children component需要傳遞這麼很多次才能傳過去,因此Context的出現,讓你輕鬆地傳遞資料到你想使用的component上面。

可是你可能會想說,我傳遞這麼多次props也沒什麼不好呀?那麼讓我們再來看官方的介紹:
In a typical React application, data is passed top-down (parent to child) via props, but such usage can be cumbersome for certain types of props (e.g. locale preference, UI theme) that are required by many components within an application. Context provides a way to share values like these between components without having to explicitly pass a prop through every level of the tree.

傳遞過多的props可能會影響效能之外,也會影響到部分的UI開發與原則。
有遇過開發程式想重構或是拆components的人應該知道什麼意思,綁住太多資料會造成開發上的不易。

什麼時候需要Context

我們來看官方的介紹:
Context is designed to share data that can be considered “global” for a tree of React components, such as the current authenticated user, theme, or preferred language.

Context就是可以讓特定的資料變成global,所有的tree components都可以使用這些資料。

使用Context前需要注意

官方敘述:
Context is primarily used when some data needs to be accessible by many components at different nesting levels. Apply it sparingly because it makes component reuse more difficult.


Comment