title: How to update state in Context using Hooks in MERN Stack Application
body: <p>I'm trying to find a way to update my &quot;user&quot; state, but I'm stuck here for 3 days already, I need some help.</p>
  <p>Here is my user context:</p>
  <pre><code>import React, {useEffect, useState} from 'react';
  
  export const UserContext = React.createContext({})
  const UserProvider = UserContext.Provider;
  
  const UserContextProvider = (props) =&gt; {
      const [user, setUser] = useState({})
      
      useEffect(() =&gt; {
          fetch(`${API}/auth/user`, {
              method: 'GET',
              withCredentials: true,
              credentials: 'include'
          })
          .then (response =&gt; response.json())
          .then (response =&gt; {
              setUser(response.user)
          })
          .catch (error =&gt; {
              console.error (error);
          });
      }, [setUser])
  
      console.log(user)
  
      return (
          &lt;UserProvider value={{user, setUser}}&gt;
              {props.children}
          &lt;/UserProvider&gt;
      )
  }   
  
  export default UserContextProvider;
  </code></pre>
  <p>Here is where I'm trying to update the user. In my case I'm trying to push an object in user.cart array, cuz everything on the back-end is fine, but in the front-end the state is not updating:</p>
  <ul>
  <li><p>First I'm using the UserContext:</p>
  <p>const Products = () =&gt; {</p>
  <pre><code>       const {user, setUser} = useContext(UserContext) ...
  </code></pre>
  </li>
  </ul>
  <p>And then here I'm trying to update the user state, BUT when I click the button it logged me out:</p>
  <pre><code>&lt;button className=&quot;addTo--Cart--Button--Container&quot;&gt;
        &lt;FaShoppingCart onClick={() =&gt; {addToCart(user._id, product); setUser(oldState =&gt; oldState.cart.push(product))}}/&gt;
  &lt;/button&gt;
  </code></pre>
  <p>After this logged me out, the <code>console.log(user)</code> which is in UserContextProvider function log only the user.cart updated lenght.</p>
  <p>AND one more:</p>
  <p>How to remove item from context:</p>
  <p>Here is my remove function:</p>
  <pre><code>const removeFromContextCart = (id) =&gt; {
          console.log(id)
          const updatedCart = user.cart.filter((item) =&gt; item.id !== id);
          setUser(oldState =&gt; ({
              ...oldState,
              cart: [
                  ...oldState.cart,
                  updatedCart
              ]
          }))
      }
  </code></pre>
  <p>And my button:</p>
  <pre><code>&lt;button className=&quot;remove--Button&quot; onClick={() =&gt; {removeFromCart(user._id, product); setUser(removeFromContextCart(product._id))}}&gt; REMOVE&lt;/button&gt;
  </code></pre>