title: Using context API (React.js) to change only a particular key in state object
body: <p>I am using context API in react for managing state. For this I have created a file <strong>AppContext.js</strong> where I have created context and Provider:</p>
  <pre><code>import { useState, createContext } from &quot;react&quot;;
  
  export const AppContext = createContext();
  
  export const AppProvider = (props) =&gt; {
     const [appdata, setAppdata] = useState({
        data1: &quot;this is data1&quot;,
        data2: &quot;this is data2&quot;,
     });
  
     return (
        &lt;AppContext.Provider value={[appdata, setAppdata]}&gt;
           {props.children}
        &lt;/AppContext.Provider&gt;
     );
  };
  </code></pre>
  <p>I have imported this Provider in the parent component of the app i.e <strong>App.js</strong>. Also I have wrapped the <code>&lt;AppChild/&gt;</code> component in the Provider.</p>
  <pre><code>import AppChild from &quot;./AppChild&quot;;
  import { AppProvider } from &quot;./AppContext&quot;;
  
  const App = () =&gt; {
     return (
        &lt;AppProvider&gt;
           &lt;div className=&quot;App&quot;&gt;hello&lt;/div&gt;
           &lt;AppChild /&gt;
        &lt;/AppProvider&gt;
     );
  };
  
  export default App;
  </code></pre>
  <p>Now from <code>AppChild</code> component, I only needed to update the <code>data1</code> key of my state. For this I have created a button with a <code>onClick</code> through which I will be changing my state. I have used to following code in <strong>AppChild.js</strong> for this:</p>
  <pre><code>import { useContext } from &quot;react&quot;;
  import { AppContext } from &quot;./AppContext&quot;;
  
  const AppChild = () =&gt; {
     const [appdata, setAppdata] = useContext(AppContext);
     return (
        &lt;div&gt;
           &lt;h3 style={{ color: &quot;red&quot; }}&gt;Data for Appchild: {appdata.data1}&lt;/h3&gt;
           &lt;button
              onClick={() =&gt;
                 setAppdata((prev) =&gt; {
                    prev.data1 = &quot;updated data1&quot;;
                    return prev;
                 })
              }
           &gt;
              click to change
           &lt;/button&gt;
        &lt;/div&gt;
     );
  };
  
  export default AppChild;
  </code></pre>
  <p>But when I click the button, the text inside the <code>&lt;h3&gt;</code> block is not changing. Although when I change the whole state by passing the whole object directly to <code>setAppdata</code> as shown below,
  <a href="https://i.stack.imgur.com/Zp2Bc.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Zp2Bc.png" alt="new code" /></a></p>
  <p>This way the state updates successfully. Why is the first method not working where I only wanted to change the <code>data1</code> key?</p>