{"id":234057,"date":"2021-04-23T16:00:07","date_gmt":"2021-04-23T13:00:07","guid":{"rendered":"https:\/\/en.buradabiliyorum.com\/how-to-use-react-contexts-to-manage-state-cloudsavvy-it\/"},"modified":"2021-04-23T16:00:07","modified_gmt":"2021-04-23T13:00:07","slug":"how-to-use-react-contexts-to-manage-state-cloudsavvy-it","status":"publish","type":"post","link":"https:\/\/buradabiliyorum.com\/en\/how-to-use-react-contexts-to-manage-state-cloudsavvy-it\/","title":{"rendered":"#How to Use React Contexts to Manage State \u2013 CloudSavvy IT"},"content":{"rendered":"<div id=\"ez-toc-container\" class=\"ez-toc-v2_0_84 counter-hierarchy ez-toc-counter ez-toc-custom ez-toc-container-direction\">\n<p class=\"ez-toc-title\" style=\"cursor:inherit\">Table of Contents<\/p>\n<label for=\"ez-toc-cssicon-toggle-item-6a29bbd1dcf28\" class=\"ez-toc-cssicon-toggle-label\"><span class=\"\"><span class=\"eztoc-hide\" style=\"display:none;\">Toggle<\/span><span class=\"ez-toc-icon-toggle-span\"><svg style=\"fill: #dd3333;color:#dd3333\" xmlns=\"http:\/\/www.w3.org\/2000\/svg\" class=\"list-377408\" width=\"20px\" height=\"20px\" viewBox=\"0 0 24 24\" fill=\"none\"><path d=\"M6 6H4v2h2V6zm14 0H8v2h12V6zM4 11h2v2H4v-2zm16 0H8v2h12v-2zM4 16h2v2H4v-2zm16 0H8v2h12v-2z\" fill=\"currentColor\"><\/path><\/svg><svg style=\"fill: #dd3333;color:#dd3333\" class=\"arrow-unsorted-368013\" xmlns=\"http:\/\/www.w3.org\/2000\/svg\" width=\"10px\" height=\"10px\" viewBox=\"0 0 24 24\" version=\"1.2\" baseProfile=\"tiny\"><path d=\"M18.2 9.3l-6.2-6.3-6.2 6.3c-.2.2-.3.4-.3.7s.1.5.3.7c.2.2.4.3.7.3h11c.3 0 .5-.1.7-.3.2-.2.3-.5.3-.7s-.1-.5-.3-.7zM5.8 14.7l6.2 6.3 6.2-6.3c.2-.2.3-.5.3-.7s-.1-.5-.3-.7c-.2-.2-.4-.3-.7-.3h-11c-.3 0-.5.1-.7.3-.2.2-.3.5-.3.7s.1.5.3.7z\"\/><\/svg><\/span><\/span><\/label><input type=\"checkbox\"  id=\"ez-toc-cssicon-toggle-item-6a29bbd1dcf28\" checked aria-label=\"Toggle\" \/><nav><ul class='ez-toc-list ez-toc-list-level-1 ' ><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-1\" href=\"https:\/\/buradabiliyorum.com\/en\/how-to-use-react-contexts-to-manage-state-cloudsavvy-it\/#An_Example_Without_Context\" >An Example Without Context<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-2\" href=\"https:\/\/buradabiliyorum.com\/en\/how-to-use-react-contexts-to-manage-state-cloudsavvy-it\/#Adding_the_Contexts_API\" >Adding the Contexts API<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-3\" href=\"https:\/\/buradabiliyorum.com\/en\/how-to-use-react-contexts-to-manage-state-cloudsavvy-it\/#Using_Context_With_Class_Components\" >Using Context With Class Components<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-4\" href=\"https:\/\/buradabiliyorum.com\/en\/how-to-use-react-contexts-to-manage-state-cloudsavvy-it\/#Updating_Context_Values\" >Updating Context Values<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-5\" href=\"https:\/\/buradabiliyorum.com\/en\/how-to-use-react-contexts-to-manage-state-cloudsavvy-it\/#Managing_Re-Renders\" >Managing Re-Renders<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-6\" href=\"https:\/\/buradabiliyorum.com\/en\/how-to-use-react-contexts-to-manage-state-cloudsavvy-it\/#Summary\" >Summary<\/a><\/li><\/ul><\/nav><\/div>\n<p><strong>&#8220;#How to Use React Contexts to Manage State \u2013 CloudSavvy IT&#8221;<\/strong><\/p>\n<div id=\"article-content-area\">\n<img loading=\"lazy\" decoding=\"async\" class=\"aligncenter size-full wp-image-8770\" data-pagespeed-lazy-src=\"https:\/\/www.cloudsavvyit.com\/p\/uploads\/2021\/01\/24b43beb.jpg?width=1200&amp;trim=1,1&amp;bg-color=000&amp;pad=1,1\" alt=\"React logo on a dark background\" width=\"1602\" height=\"902\" src=\"\/pagespeed_static\/1.JiBnMqyl6S.gif\" onload=\"pagespeed.lazyLoadImages.loadIfVisibleAndMaybeBeacon(this);\" onerror=\"this.onerror=null;pagespeed.lazyLoadImages.loadIfVisibleAndMaybeBeacon(this);\"\/><\/p>\n<p>React contexts are a feature which help you eliminate repetitive prop drilling. Props are often passed down from a parent component to a deeply nested child. This requires each inter<a href=\"https:\/\/buradabiliyorum.com\/en\/category\/social-mediaa\/\" data-internallinksmanager029f6b8e52c=\"1\" title=\"Social Media\" target=\"_blank\" rel=\"noopener\">media<\/a>ry component to \u201cforward\u201d the prop to the next component in the tree.<\/p>\n<p><a rel=\"nofollow noopener\" target=\"_blank\" href=\"https:\/\/reactjs.org\/docs\/context.html\">Contexts let you<\/a> pass props through the tree without manually forwarding them at each level. This is particularly useful for data representing top-level <a href=\"https:\/\/buradabiliyorum.com\/en\/category\/download-scripts-themes-apps\/\" data-internallinksmanager029f6b8e52c=\"9\" title=\"Download Scripts &amp; Themes &amp; Apps\" target=\"_blank\" rel=\"noopener\">app<\/a>lication state. User settings, authentication tokens and data cached from API responses are good candidates for the Context API.<\/p>\n<p>This data is often managed by a dedicated state store such as Redux. React\u2019s contexts can often be used instead. This removes a significant amount of complexity within apps where Redux is only used to hold application-level state. Instead of creating an action, dispatcher and reducer, you can use a React context.<\/p>\n<h2 id=\"an-example-without-context\"><span class=\"ez-toc-section\" id=\"An_Example_Without_Context\"><\/span>An Example Without Context<span class=\"ez-toc-section-end\"><\/span><\/h2>\n<p>After a user logs in, you\u2019ll often want to store essential data such as their name and email address in your app\u2019s state. This allows each component to display information about the user without making a round-<a href=\"https:\/\/buradabiliyorum.com\/en\/category\/trip-and-travel\/\" data-internallinksmanager029f6b8e52c=\"10\" title=\"Trip &amp; Travel\" target=\"_blank\" rel=\"noopener\">trip<\/a> to your API server.<\/p>\n<p>Here\u2019s a naive way of implementing this:<\/p>\n<div class=\"wp-geshi-highlight-wrap5\">\n<div class=\"wp-geshi-highlight-wrap4\">\n<div class=\"wp-geshi-highlight-wrap3\">\n<div class=\"wp-geshi-highlight-wrap2\">\n<div class=\"wp-geshi-highlight-wrap\">\n<div class=\"wp-geshi-highlight\">\n<div class=\"javascript\">\n<pre class=\"de1\"><span class=\"kw1\">const<\/span> UserProfileLink <span class=\"sy0\">=<\/span> <span class=\"br0\">(<\/span><span class=\"br0\">{<\/span>user<span class=\"br0\">}<\/span><span class=\"br0\">)<\/span> <span class=\"sy0\">=&gt;<\/span> <span class=\"br0\">{<\/span>\n    <span class=\"kw1\">return<\/span> <span class=\"br0\">(<\/span>\n        <span class=\"sy0\">&lt;<\/span>div<span class=\"sy0\">&gt;<\/span>\n            <span class=\"sy0\">&lt;<\/span>p<span class=\"sy0\">&gt;<\/span>Logged <span class=\"kw1\">in<\/span> as <span class=\"br0\">{<\/span>user.<span class=\"me1\">Name<\/span><span class=\"br0\">}<\/span><span class=\"sy0\">&lt;\/<\/span>p<span class=\"sy0\">&gt;<\/span>\n            <span class=\"sy0\">&lt;<\/span>a href<span class=\"sy0\">=<\/span><span class=\"st0\">\"\/logout\"<\/span><span class=\"sy0\">&gt;<\/span>Logout<span class=\"sy0\">&lt;\/<\/span>a<span class=\"sy0\">&gt;<\/span>\n        <span class=\"sy0\">&lt;\/<\/span>div<span class=\"sy0\">&gt;<\/span>\n    <span class=\"br0\">)<\/span><span class=\"sy0\">;<\/span>\n<span class=\"br0\">}<\/span><span class=\"sy0\">;<\/span>\n\u00a0\n<span class=\"kw1\">const<\/span> Header <span class=\"sy0\">=<\/span> <span class=\"br0\">(<\/span><span class=\"br0\">{<\/span>user<span class=\"br0\">}<\/span><span class=\"br0\">)<\/span> <span class=\"sy0\">=&gt;<\/span> <span class=\"br0\">{<\/span>\n    <span class=\"kw1\">return<\/span> <span class=\"br0\">(<\/span>\n        <span class=\"sy0\">&lt;<\/span>div<span class=\"sy0\">&gt;<\/span>\n            <span class=\"sy0\">&lt;<\/span>h1<span class=\"sy0\">&gt;<\/span>My App<span class=\"sy0\">&lt;\/<\/span>h1<span class=\"sy0\">&gt;<\/span>\n            <span class=\"sy0\">&lt;<\/span>UserProfileLink user<span class=\"sy0\">=<\/span><span class=\"br0\">{<\/span>user<span class=\"br0\">}<\/span> <span class=\"sy0\">\/&gt;<\/span>\n        <span class=\"sy0\">&lt;\/<\/span>div<span class=\"sy0\">&gt;<\/span>\n    <span class=\"br0\">)<\/span><span class=\"sy0\">;<\/span>\n<span class=\"br0\">}<\/span>\n\u00a0\n<span class=\"kw1\">const<\/span> App <span class=\"sy0\">=<\/span> <span class=\"br0\">(<\/span><span class=\"br0\">)<\/span> <span class=\"sy0\">=&gt;<\/span> <span class=\"br0\">{<\/span>\n    <span class=\"kw1\">const<\/span> <span class=\"br0\">[<\/span>user<span class=\"sy0\">,<\/span> setUser<span class=\"br0\">]<\/span> <span class=\"sy0\">=<\/span> useState<span class=\"br0\">(<\/span><span class=\"br0\">{<\/span>\n        Name<span class=\"sy0\">:<\/span> <span class=\"st0\">\"Foo Bar\"<\/span><span class=\"sy0\">,<\/span>\n        Email<span class=\"sy0\">:<\/span> <span class=\"st0\">\"foobar@example.com\"<\/span>\n    <span class=\"br0\">}<\/span><span class=\"br0\">)<\/span><span class=\"sy0\">;<\/span>\n    <span class=\"kw1\">return<\/span> <span class=\"sy0\">&lt;<\/span>Header user<span class=\"sy0\">=<\/span><span class=\"br0\">{<\/span>user<span class=\"br0\">}<\/span> <span class=\"sy0\">\/&gt;<\/span>\n<span class=\"br0\">}<\/span><\/pre>\n<\/div>\n<\/div>\n<\/div>\n<\/div>\n<\/div>\n<\/div>\n<\/div>\n<p>There are three components in the app. The top-level <code>App<\/code> component keeps track of the current user within its state. It renders the <code>Header<\/code> component. <code>Header<\/code> renders <code>UserProfileLink<\/code>, which displays the user\u2019s name.<\/p>\n<p>Crucially, only <code>UserProfileLink<\/code> actually interacts with the user object. <code>Header<\/code> still has to receive a <code>user<\/code> prop though. This is then forwarded straight into <code>UserProfileLink<\/code>, without being consumed by <code>Header<\/code>.<\/p>\n<p>The problems with this approach are exasperated as your component tree becomes more complex. You might forward props through multiple nested levels, even though the intermediary components don\u2019t use the props themselves.<\/p>\n<h2 id=\"adding-the-contexts-api\"><span class=\"ez-toc-section\" id=\"Adding_the_Contexts_API\"><\/span>Adding the Contexts API<span class=\"ez-toc-section-end\"><\/span><\/h2>\n<p>You can mitigate these issues using the Contexts API. We can refactor the example above to remove the <code>user<\/code> prop from <code>Header<\/code>.<\/p>\n<p>The <code>App<\/code> component will create a new context to store the current user object. <code>UserProfileLink<\/code> will consume the context. The component will be able to access the user data provided by the context. This is a similar concept to connecting a component to a Redux store.<\/p>\n<div class=\"wp-geshi-highlight-wrap5\">\n<div class=\"wp-geshi-highlight-wrap4\">\n<div class=\"wp-geshi-highlight-wrap3\">\n<div class=\"wp-geshi-highlight-wrap2\">\n<div class=\"wp-geshi-highlight-wrap\">\n<div class=\"wp-geshi-highlight\">\n<div class=\"javascript\">\n<pre class=\"de1\"><span class=\"kw1\">const<\/span> UserContext <span class=\"sy0\">=<\/span> React.<span class=\"me1\">createContext<\/span><span class=\"br0\">(<\/span><span class=\"kw2\">null<\/span><span class=\"br0\">)<\/span><span class=\"sy0\">;<\/span>\n\u00a0\n<span class=\"kw1\">const<\/span> UserProfileLink <span class=\"sy0\">=<\/span> <span class=\"br0\">(<\/span><span class=\"br0\">)<\/span> <span class=\"sy0\">=&gt;<\/span> <span class=\"br0\">{<\/span>\n    <span class=\"kw1\">const<\/span> user <span class=\"sy0\">=<\/span> useContext<span class=\"br0\">(<\/span>UserContext<span class=\"br0\">)<\/span><span class=\"sy0\">;<\/span>\n    <span class=\"kw1\">return<\/span> <span class=\"br0\">(<\/span>\n        <span class=\"sy0\">&lt;<\/span>div<span class=\"sy0\">&gt;<\/span>\n            <span class=\"sy0\">&lt;<\/span>p<span class=\"sy0\">&gt;<\/span>Logged <span class=\"kw1\">in<\/span> as <span class=\"br0\">{<\/span>user.<span class=\"me1\">Name<\/span><span class=\"br0\">}<\/span><span class=\"sy0\">&lt;\/<\/span>p<span class=\"sy0\">&gt;<\/span>\n            <span class=\"sy0\">&lt;<\/span>a href<span class=\"sy0\">=<\/span><span class=\"st0\">\"\/logout\"<\/span><span class=\"sy0\">&gt;<\/span>Logout<span class=\"sy0\">&lt;\/<\/span>a<span class=\"sy0\">&gt;<\/span>\n        <span class=\"sy0\">&lt;\/<\/span>div<span class=\"sy0\">&gt;<\/span>\n    <span class=\"br0\">)<\/span><span class=\"sy0\">;<\/span>\n<span class=\"br0\">}<\/span><span class=\"sy0\">;<\/span>\n\u00a0\n<span class=\"kw1\">const<\/span> Header <span class=\"sy0\">=<\/span> <span class=\"br0\">(<\/span><span class=\"br0\">)<\/span> <span class=\"sy0\">=&gt;<\/span> <span class=\"br0\">{<\/span>\n    <span class=\"kw1\">return<\/span> <span class=\"br0\">(<\/span>\n        <span class=\"sy0\">&lt;<\/span>div<span class=\"sy0\">&gt;<\/span>\n            <span class=\"sy0\">&lt;<\/span>h1<span class=\"sy0\">&gt;<\/span>My App<span class=\"sy0\">&lt;\/<\/span>h1<span class=\"sy0\">&gt;<\/span>\n            <span class=\"sy0\">&lt;<\/span>UserProfileLink <span class=\"sy0\">\/&gt;<\/span>\n        <span class=\"sy0\">&lt;\/<\/span>div<span class=\"sy0\">&gt;<\/span>\n    <span class=\"br0\">)<\/span><span class=\"sy0\">;<\/span>\n<span class=\"br0\">}<\/span>\n\u00a0\n<span class=\"kw1\">const<\/span> App <span class=\"sy0\">=<\/span> <span class=\"br0\">(<\/span><span class=\"br0\">)<\/span> <span class=\"sy0\">=&gt;<\/span> <span class=\"br0\">{<\/span>\n\u00a0\n    <span class=\"kw1\">const<\/span> <span class=\"br0\">[<\/span>user<span class=\"sy0\">,<\/span> setUser<span class=\"br0\">]<\/span> <span class=\"sy0\">=<\/span> useState<span class=\"br0\">(<\/span><span class=\"br0\">{<\/span>\n        Name<span class=\"sy0\">:<\/span> <span class=\"st0\">\"Foo Bar\"<\/span><span class=\"sy0\">,<\/span>\n        Email<span class=\"sy0\">:<\/span> <span class=\"st0\">\"foobar@example.com\"<\/span>\n    <span class=\"br0\">}<\/span><span class=\"br0\">)<\/span><span class=\"sy0\">;<\/span>\n\u00a0\n    <span class=\"kw1\">return<\/span> <span class=\"br0\">(<\/span>\n        <span class=\"sy0\">&lt;<\/span>UserContext.<span class=\"me1\">Provider<\/span> value<span class=\"sy0\">=<\/span><span class=\"br0\">{<\/span>user<span class=\"br0\">}<\/span><span class=\"sy0\">&gt;<\/span>\n            <span class=\"sy0\">&lt;<\/span>Header <span class=\"sy0\">\/&gt;<\/span>\n        <span class=\"sy0\">&lt;\/<\/span>UserContext<span class=\"sy0\">&gt;<\/span>\n    <span class=\"br0\">)<\/span><span class=\"sy0\">;<\/span>\n\u00a0\n<span class=\"br0\">}<\/span><\/pre>\n<\/div>\n<\/div>\n<\/div>\n<\/div>\n<\/div>\n<\/div>\n<\/div>\n<p>This refactored set of components illustrates how to use Contexts.<\/p>\n<p>The process starts by creating a new context for the value you\u2019d like to make available. The call to <code>React.createContext(null)<\/code> sets up a new context with a default value of <code>null<\/code>.<\/p>\n<p>The <code>App<\/code> component has been rewritten to wrap <code>Header<\/code> in <code>UserContext.Provider<\/code>. The <code>value<\/code> prop determines the current value of the context. This is set to the <code>user<\/code> object held in state. Any components nested below the context provider can now consume the context and access the user object.<\/p>\n<p>If you try to access the context from a component that\u2019s not nested within a provider instance, the component will receive the default value you passed to <code>createContext()<\/code>. This should <a href=\"https:\/\/buradabiliyorum.com\/en\/category\/general\/\" data-internallinksmanager029f6b8e52c=\"3\" title=\"General\" target=\"_blank\" rel=\"noopener\">general<\/a>ly be avoided except for static context values which will never change.<\/p>\n<p>Access to the provided context value is observed in <code>UserProfileLink<\/code>. The <code>user<\/code> prop has been removed. The component uses React\u2019s <a rel=\"nofollow noopener\" target=\"_blank\" href=\"https:\/\/reactjs.org\/docs\/hooks-reference.html#usecontext\">useContext() hook<\/a> to retrieve the current value of the <code>UserContext<\/code>. This will provide the user object injected by the <code>App<\/code> component!<\/p>\n<p>The final change is to the <code>Header<\/code> component. This no longer needs to forward the <code>user<\/code> prop so it can be removed entirely. In fact, the <code>user<\/code> prop is gone from the entire app. It\u2019s now fed by <code>App<\/code> into the <code>UserContext<\/code> provider, not any specific component.<\/p>\n<h2 id=\"using-context-with-class-components\"><span class=\"ez-toc-section\" id=\"Using_Context_With_Class_Components\"><\/span>Using Context With Class Components<span class=\"ez-toc-section-end\"><\/span><\/h2>\n<p>So far we\u2019ve only used contexts within functional components. Contexts work well here as the <code>useContext()<\/code> hook simplifies accessing the provided data within child components.<\/p>\n<p>You can also use contexts with class components. The preferred way is to set the static <code>contextType<\/code> class property to the context instance you want to use. React will read this property and set the <code>context<\/code> property on component instances to the current value provided by the context.<\/p>\n<div class=\"wp-geshi-highlight-wrap5\">\n<div class=\"wp-geshi-highlight-wrap4\">\n<div class=\"wp-geshi-highlight-wrap3\">\n<div class=\"wp-geshi-highlight-wrap2\">\n<div class=\"wp-geshi-highlight-wrap\">\n<div class=\"wp-geshi-highlight\">\n<div class=\"javascript\">\n<pre class=\"de1\"><span class=\"kw1\">const<\/span> UserContext <span class=\"sy0\">=<\/span> React.<span class=\"me1\">createContext<\/span><span class=\"br0\">(<\/span><span class=\"br0\">{<\/span>Name<span class=\"sy0\">:<\/span> <span class=\"st0\">\"Foo Bar\"<\/span><span class=\"br0\">}<\/span><span class=\"br0\">)<\/span><span class=\"sy0\">;<\/span>\n\u00a0\n<span class=\"kw5\">class<\/span> MyComponent <span class=\"kw5\">extends<\/span> React.<span class=\"me1\">Component<\/span> <span class=\"br0\">{<\/span>\n\u00a0\n    <span class=\"co1\">\/\/ Tell React to inject the `UserContext` value<\/span>\n    <span class=\"kw1\">static<\/span> contextType <span class=\"sy0\">=<\/span> UserContext<span class=\"sy0\">;<\/span>\n\u00a0\n    render<span class=\"br0\">(<\/span><span class=\"br0\">)<\/span> <span class=\"br0\">{<\/span>\n        <span class=\"co1\">\/\/ Requested context value made available as `this.context`<\/span>\n        <span class=\"kw1\">return<\/span> <span class=\"sy0\">&lt;<\/span>p<span class=\"sy0\">&gt;<\/span><span class=\"br0\">{<\/span><span class=\"kw1\">this<\/span>.<span class=\"me1\">context<\/span>.<span class=\"me1\">Name<\/span><span class=\"br0\">}<\/span><span class=\"sy0\">&lt;\/<\/span>p<span class=\"sy0\">&gt;;<\/span>\n    <span class=\"br0\">}<\/span>\n\u00a0\n<span class=\"br0\">}<\/span><\/pre>\n<\/div>\n<\/div>\n<\/div>\n<\/div>\n<\/div>\n<\/div>\n<\/div>\n<p>An alternative approach is to render your component\u2019s children within a <a rel=\"nofollow noopener\" target=\"_blank\" href=\"https:\/\/reactjs.org\/docs\/context.html#contextconsumer\">context \u201cconsumer\u201d<\/a>. You can access each context\u2019s consumer as the <code>Consumer<\/code> property of the context instance.<\/p>\n<p>You must provide a <em>function<\/em> as the consumer\u2019s child. The function will be called with the context\u2019s value when the component renders.<\/p>\n<p>Here\u2019s what this looks like:<\/p>\n<div class=\"wp-geshi-highlight-wrap5\">\n<div class=\"wp-geshi-highlight-wrap4\">\n<div class=\"wp-geshi-highlight-wrap3\">\n<div class=\"wp-geshi-highlight-wrap2\">\n<div class=\"wp-geshi-highlight-wrap\">\n<div class=\"wp-geshi-highlight\">\n<div class=\"javascript\">\n<pre class=\"de1\"><span class=\"kw1\">const<\/span> UserContext <span class=\"sy0\">=<\/span> React.<span class=\"me1\">createContext<\/span><span class=\"br0\">(<\/span><span class=\"br0\">{<\/span>Name<span class=\"sy0\">:<\/span> <span class=\"st0\">\"Foo Bar\"<\/span><span class=\"br0\">}<\/span><span class=\"br0\">)<\/span><span class=\"sy0\">;<\/span>\n\u00a0\n<span class=\"kw5\">class<\/span> MyComponent <span class=\"kw5\">extends<\/span> React.<span class=\"me1\">Component<\/span> <span class=\"br0\">{<\/span>\n\u00a0\n    render<span class=\"br0\">(<\/span><span class=\"br0\">)<\/span> <span class=\"br0\">{<\/span>\n        <span class=\"kw1\">return<\/span> <span class=\"br0\">(<\/span>\n            <span class=\"sy0\">&lt;<\/span>UserContext.<span class=\"me1\">Consumer<\/span><span class=\"sy0\">&gt;<\/span>\n                <span class=\"br0\">{<\/span>user <span class=\"sy0\">=&gt;<\/span> <span class=\"sy0\">&lt;<\/span>p<span class=\"sy0\">&gt;<\/span><span class=\"br0\">{<\/span>user.<span class=\"me1\">Name<\/span><span class=\"br0\">}<\/span><span class=\"sy0\">&lt;\/<\/span>p<span class=\"sy0\">&gt;<\/span><span class=\"br0\">}<\/span>\n            <span class=\"sy0\">&lt;\/<\/span>UserContext.<span class=\"me1\">Consumer<\/span><span class=\"sy0\">&gt;<\/span>\n        <span class=\"br0\">)<\/span><span class=\"sy0\">;<\/span>\n    <span class=\"br0\">}<\/span>\n\u00a0\n<span class=\"br0\">}<\/span><\/pre>\n<\/div>\n<\/div>\n<\/div>\n<\/div>\n<\/div>\n<\/div>\n<\/div>\n<p>Using <code>contextType<\/code> restricts you to one context per component. Context consumers address this issue but can make your component\u2019s render method more opaque. Neither approach is quite as straightforward as the <code>useContext()<\/code> hook available to functional components.<\/p>\n<h2 id=\"updating-context-values\"><span class=\"ez-toc-section\" id=\"Updating_Context_Values\"><\/span>Updating Context Values<span class=\"ez-toc-section-end\"><\/span><\/h2>\n<p>Context values function similarly to props. If a child needs to update context values, add a function to the context. The child could call the function to effect the context value change.<\/p>\n<div class=\"wp-geshi-highlight-wrap5\">\n<div class=\"wp-geshi-highlight-wrap4\">\n<div class=\"wp-geshi-highlight-wrap3\">\n<div class=\"wp-geshi-highlight-wrap2\">\n<div class=\"wp-geshi-highlight-wrap\">\n<div class=\"wp-geshi-highlight\">\n<div class=\"javascript\">\n<pre class=\"de1\"><span class=\"kw1\">const<\/span> UserContext <span class=\"sy0\">=<\/span> React.<span class=\"me1\">createContext<\/span><span class=\"br0\">(<\/span><span class=\"kw2\">null<\/span><span class=\"br0\">)<\/span><span class=\"sy0\">;<\/span>\n\u00a0\n<span class=\"kw1\">const<\/span> UserProfileLink <span class=\"sy0\">=<\/span> <span class=\"br0\">(<\/span><span class=\"br0\">)<\/span> <span class=\"sy0\">=&gt;<\/span> <span class=\"br0\">{<\/span>\n    <span class=\"kw1\">const<\/span> context <span class=\"sy0\">=<\/span> useContext<span class=\"br0\">(<\/span>UserContext<span class=\"br0\">)<\/span><span class=\"sy0\">;<\/span>\n    <span class=\"kw1\">return<\/span> <span class=\"br0\">(<\/span>\n        <span class=\"sy0\">&lt;<\/span>div<span class=\"sy0\">&gt;<\/span>\n            <span class=\"sy0\">&lt;<\/span>p<span class=\"sy0\">&gt;<\/span>Logged <span class=\"kw1\">in<\/span> as <span class=\"br0\">{<\/span>context.<span class=\"me1\">user<\/span>.<span class=\"me1\">Name<\/span><span class=\"br0\">}<\/span><span class=\"sy0\">&lt;\/<\/span>p<span class=\"sy0\">&gt;<\/span>\n            <span class=\"sy0\">&lt;<\/span>a onClick<span class=\"sy0\">=<\/span><span class=\"br0\">{<\/span><span class=\"br0\">(<\/span><span class=\"br0\">)<\/span> <span class=\"sy0\">=&gt;<\/span> context.<span class=\"me1\">logoutUser<\/span><span class=\"br0\">(<\/span><span class=\"br0\">)<\/span><span class=\"br0\">}<\/span><span class=\"sy0\">&gt;<\/span>Logout<span class=\"sy0\">&lt;\/<\/span>a<span class=\"sy0\">&gt;<\/span>\n        <span class=\"sy0\">&lt;\/<\/span>div<span class=\"sy0\">&gt;<\/span>\n    <span class=\"br0\">)<\/span><span class=\"sy0\">;<\/span>\n<span class=\"br0\">}<\/span><span class=\"sy0\">;<\/span>\n\u00a0\n<span class=\"kw1\">const<\/span> Header <span class=\"sy0\">=<\/span> <span class=\"br0\">(<\/span><span class=\"br0\">)<\/span> <span class=\"sy0\">=&gt;<\/span> <span class=\"br0\">{<\/span>\n    <span class=\"kw1\">return<\/span> <span class=\"br0\">(<\/span>\n        <span class=\"sy0\">&lt;<\/span>div<span class=\"sy0\">&gt;<\/span>\n            <span class=\"sy0\">&lt;<\/span>h1<span class=\"sy0\">&gt;<\/span>My App<span class=\"sy0\">&lt;\/<\/span>h1<span class=\"sy0\">&gt;<\/span>\n            <span class=\"sy0\">&lt;<\/span>UserProfileLink <span class=\"sy0\">\/&gt;<\/span>\n        <span class=\"sy0\">&lt;\/<\/span>div<span class=\"sy0\">&gt;<\/span>\n    <span class=\"br0\">)<\/span><span class=\"sy0\">;<\/span>\n<span class=\"br0\">}<\/span>\n\u00a0\n<span class=\"kw1\">const<\/span> App <span class=\"sy0\">=<\/span> <span class=\"br0\">(<\/span><span class=\"br0\">)<\/span> <span class=\"sy0\">=&gt;<\/span> <span class=\"br0\">{<\/span>\n\u00a0\n    <span class=\"kw1\">const<\/span> <span class=\"br0\">[<\/span>user<span class=\"sy0\">,<\/span> setUser<span class=\"br0\">]<\/span> <span class=\"sy0\">=<\/span> useState<span class=\"br0\">(<\/span><span class=\"br0\">{<\/span>\n        Name<span class=\"sy0\">:<\/span> <span class=\"st0\">\"Foo Bar\"<\/span><span class=\"sy0\">,<\/span>\n        Email<span class=\"sy0\">:<\/span> <span class=\"st0\">\"foobar@example.com\"<\/span>\n    <span class=\"br0\">}<\/span><span class=\"br0\">)<\/span><span class=\"sy0\">;<\/span>\n\u00a0\n    <span class=\"kw1\">const<\/span> contextValue <span class=\"sy0\">=<\/span> <span class=\"br0\">{<\/span>\n        user<span class=\"sy0\">,<\/span>\n        logoutUser<span class=\"sy0\">:<\/span> <span class=\"br0\">(<\/span><span class=\"br0\">)<\/span> <span class=\"sy0\">=&gt;<\/span> setUser<span class=\"br0\">(<\/span><span class=\"kw2\">null<\/span><span class=\"br0\">)<\/span>\n    <span class=\"br0\">}<\/span>\n\u00a0\n    <span class=\"kw1\">return<\/span> <span class=\"br0\">(<\/span>\n        <span class=\"sy0\">&lt;<\/span>UserContext.<span class=\"me1\">Provider<\/span> value<span class=\"sy0\">=<\/span><span class=\"br0\">{<\/span>contextValue<span class=\"br0\">}<\/span><span class=\"sy0\">&gt;<\/span>\n            <span class=\"sy0\">&lt;<\/span>Header <span class=\"sy0\">\/&gt;<\/span>\n        <span class=\"sy0\">&lt;\/<\/span>UserContext<span class=\"sy0\">&gt;<\/span>\n    <span class=\"br0\">)<\/span><span class=\"sy0\">;<\/span>\n\u00a0\n<span class=\"br0\">}<\/span><\/pre>\n<\/div>\n<\/div>\n<\/div>\n<\/div>\n<\/div>\n<\/div>\n<\/div>\n<p>This revised example shows how <code>App<\/code> now provides a <code>logoutUser<\/code> function within the context. Context consumers can call this function to update the <code>user<\/code> in the <code>App<\/code> component\u2019s state, causing the context\u2019s value to be modified accordingly.<\/p>\n<h2 id=\"managing-re-renders\"><span class=\"ez-toc-section\" id=\"Managing_Re-Renders\"><\/span>Managing Re-Renders<span class=\"ez-toc-section-end\"><\/span><\/h2>\n<p>React will re-render all children of a context provider whenever the provider\u2019s <code>value<\/code> prop changes. Value changes are compared using <code>Object.is()<\/code>, which means you must take care when using objects as the context provider\u2019s <code>value<\/code>.<\/p>\n<div class=\"wp-geshi-highlight-wrap5\">\n<div class=\"wp-geshi-highlight-wrap4\">\n<div class=\"wp-geshi-highlight-wrap3\">\n<div class=\"wp-geshi-highlight-wrap2\">\n<div class=\"wp-geshi-highlight-wrap\">\n<div class=\"wp-geshi-highlight\">\n<div class=\"javascript\">\n<pre class=\"de1\"><span class=\"kw1\">const<\/span> App <span class=\"sy0\">=<\/span> <span class=\"br0\">(<\/span><span class=\"br0\">)<\/span> <span class=\"sy0\">=&gt;<\/span> <span class=\"br0\">{<\/span>\n    <span class=\"kw1\">return<\/span> <span class=\"br0\">(<\/span>\n        <span class=\"sy0\">&lt;<\/span>ExampleContext.<span class=\"me1\">Provider<\/span> value<span class=\"sy0\">=<\/span><span class=\"br0\">{<\/span><span class=\"br0\">{<\/span>foo<span class=\"sy0\">:<\/span> <span class=\"st0\">\"bar\"<\/span><span class=\"br0\">}<\/span><span class=\"br0\">}<\/span><span class=\"sy0\">&gt;<\/span>\n            <span class=\"sy0\">&lt;<\/span>NestedComponent <span class=\"sy0\">\/&gt;<\/span>\n        <span class=\"sy0\">&lt;\/<\/span>ExampleContext.<span class=\"me1\">Provider<\/span><span class=\"sy0\">&gt;<\/span>\n    <span class=\"br0\">)<\/span><span class=\"sy0\">;<\/span>\n<span class=\"br0\">}<\/span><\/pre>\n<\/div>\n<\/div>\n<\/div>\n<\/div>\n<\/div>\n<\/div>\n<\/div>\n<p>This component would re-render <code>NestedComponent<\/code> every time <code>App<\/code> renders. A <em>new<\/em> object instance is created for the provider\u2019s <code>value<\/code> prop each time, so React re-renders the component\u2019s children.<\/p>\n<p>You can address this by lifting the <code>value<\/code> object into the component\u2019s state. This will ensure the <em>same<\/em> object is rendered each time:<\/p>\n<div class=\"wp-geshi-highlight-wrap5\">\n<div class=\"wp-geshi-highlight-wrap4\">\n<div class=\"wp-geshi-highlight-wrap3\">\n<div class=\"wp-geshi-highlight-wrap2\">\n<div class=\"wp-geshi-highlight-wrap\">\n<div class=\"wp-geshi-highlight\">\n<div class=\"javascript\">\n<pre class=\"de1\"><span class=\"kw1\">const<\/span> App <span class=\"sy0\">=<\/span> <span class=\"br0\">(<\/span><span class=\"br0\">)<\/span> <span class=\"sy0\">=&gt;<\/span> <span class=\"br0\">{<\/span>\n    <span class=\"kw1\">const<\/span> <span class=\"br0\">[<\/span>obj<span class=\"sy0\">,<\/span> setObj<span class=\"br0\">]<\/span> <span class=\"sy0\">=<\/span> useState<span class=\"br0\">(<\/span><span class=\"br0\">{<\/span>foo<span class=\"sy0\">:<\/span> <span class=\"st0\">\"bar\"<\/span><span class=\"br0\">}<\/span><span class=\"br0\">)<\/span><span class=\"sy0\">;<\/span>\n    <span class=\"kw1\">return<\/span> <span class=\"br0\">(<\/span>\n        <span class=\"sy0\">&lt;<\/span>ExampleContext.<span class=\"me1\">Provider<\/span> value<span class=\"sy0\">=<\/span><span class=\"br0\">{<\/span>obj<span class=\"br0\">}<\/span><span class=\"sy0\">&gt;<\/span>\n            <span class=\"sy0\">&lt;<\/span>NestedComponent <span class=\"sy0\">\/&gt;<\/span>\n        <span class=\"sy0\">&lt;\/<\/span>ExampleContext.<span class=\"me1\">Provider<\/span><span class=\"sy0\">&gt;<\/span>\n    <span class=\"br0\">)<\/span><span class=\"sy0\">;<\/span>\n<span class=\"br0\">}<\/span><\/pre>\n<\/div>\n<\/div>\n<\/div>\n<\/div>\n<\/div>\n<\/div>\n<\/div>\n<h2 id=\"summary\"><span class=\"ez-toc-section\" id=\"Summary\"><\/span>Summary<span class=\"ez-toc-section-end\"><\/span><\/h2>\n<p>React Contexts help you cut out prop drilling by providing a first-class way to pass data down the component tree. Contexts are a good alternative to state libraries like Redux. They\u2019re built-in to React and are gaining traction among projects where Redux is used solely to connect deeply nested components to a shared source of state.<\/p>\n<p>Contexts are intended for \u201cglobal\u201d data held within your application. They may also hold data for a specific sub-section of your app. Contexts aren\u2019t meant to replace local component state entirely. Individual components should continue to use state and props where the data\u2019s only going to pass up and down a shallowly nested tree.\n<\/p><\/div>\n<blockquote><p><strong><span style=\"color: #ff6600;\">If you liked the article, do not forget to share it with your friends. Follow us on\u00a0<span style=\"color: #ff0000;\"><a style=\"color: #ff0000;\" href=\"https:\/\/news.google.com\/publications\/CAAqBwgKMLG0nwswvr63Aw\" target=\"_blank\" rel=\"nofollow noopener noreferrer\">Google News<\/a><\/span>\u00a0too, click on the star and choose us from your favorites.<\/span><\/strong><\/p><\/blockquote>\n<blockquote>\n<p style=\"text-align: center;\">For forums sites go to <span style=\"color: #ff9900;\"><a style=\"color: #ff9900;\" href=\"https:\/\/forum.buradabiliyorum.com\/\" target=\"_blank\" rel=\"noopener\">Forum.BuradaBiliyorum.Com<\/a><\/span><\/strong><\/p>\n<\/blockquote>\n<blockquote>\n<p style=\"text-align: center;\"><strong>If you want to read more like this article, you can visit our <span style=\"color: #ff9900;\"><a style=\"color: #ff9900;\" href=\"https:\/\/en.buradabiliyorum.com\/technology\/\" target=\"_blank\" rel=\"noopener\">Technology category.<\/a><\/span><\/strong><\/p>\n<\/blockquote>\n<p><span style=\"color: black;\"><a style=\"color: #ff9900;\" href=\"https:\/\/www.cloudsavvyit.com\/10680\/how-to-use-react-contexts-to-manage-state\/\" target=\"_blank\" rel=\"noopener\">Source<\/a><\/span><\/p>\n","protected":false},"excerpt":{"rendered":"<p>&#8220;#How to Use React Contexts to Manage State \u2013 CloudSavvy IT&#8221; React contexts are a feature which help you eliminate repetitive prop drilling. Props are often passed down from a parent component to a deeply nested child. This requires each intermediary component to \u201cforward\u201d the prop to the next component in the tree. Contexts let&#8230;<\/p>\n","protected":false},"author":1,"featured_media":234058,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"fifu_image_url":"https:\/\/www.cloudsavvyit.com\/p\/uploads\/2021\/01\/24b43beb.jpg","fifu_image_alt":"","footnotes":""},"categories":[18],"tags":[],"class_list":["post-234057","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-technology"],"_links":{"self":[{"href":"https:\/\/buradabiliyorum.com\/en\/wp-json\/wp\/v2\/posts\/234057","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/buradabiliyorum.com\/en\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/buradabiliyorum.com\/en\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/buradabiliyorum.com\/en\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/buradabiliyorum.com\/en\/wp-json\/wp\/v2\/comments?post=234057"}],"version-history":[{"count":0,"href":"https:\/\/buradabiliyorum.com\/en\/wp-json\/wp\/v2\/posts\/234057\/revisions"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/buradabiliyorum.com\/en\/wp-json\/wp\/v2\/media\/234058"}],"wp:attachment":[{"href":"https:\/\/buradabiliyorum.com\/en\/wp-json\/wp\/v2\/media?parent=234057"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/buradabiliyorum.com\/en\/wp-json\/wp\/v2\/categories?post=234057"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/buradabiliyorum.com\/en\/wp-json\/wp\/v2\/tags?post=234057"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}