title: React state and user is lost on page refresh or redirect home, using React Context API
body: <p>I login with a valid username, password.<br />
  The Navbar changes to Welcome user and a Logout Navlink button.<br />
  Clicking on Home in Nav top left or refreshing the page loses the User object and the Navbar reads Login &amp; Signup, even though user was not explicitly logged out</p>
  <p>How to fix state management with <strong>react hooks</strong> as seen in examples without using alternatives such as localstorage, cookies, Auth0?</p>
  <p>App.js</p>
  <pre><code>import './App.css';
  import React, { useState, Component, useEffect } from 'react';
  import { useDispatch, useSelector } from 'react-redux';
  import { Route, Switch, Redirect } from &quot;react-router-dom&quot;;
  import { LinkContainer } from &quot;react-router-bootstrap&quot;;
  import Navbar from &quot;react-bootstrap/Navbar&quot;;
  import Nav from &quot;react-bootstrap/Nav&quot;;
  import axios from 'axios'
  import Home from &quot;./containers/Home&quot;;
  import Login from &quot;./containers/Login&quot;;
  import Signup from &quot;./containers/Signup&quot;;
  import Rooms from './containers/Rooms';
  import RoomShow from './containers/RoomShow';
  import UserContext from './context/UserContext'
  
  function App() {
    const [user, setUser] = useState(null);
    const [allChannels, setAllChannels] = useState([]);
    const [currentChannel, setCurrentChannel] = useState([]);
    
     const handleLogin = (data) =&gt; {
      setUser({
        user: data
      });
      fetch('/channels')
      .then(response =&gt; response.json())
      .then(result =&gt; {
        setAllChannels(result);
      })
    };
  
    const handleLogout = () =&gt; {
      setUser(null);   
    };
  
    const getRoomData = (id) =&gt; {
      fetch(`/rooms/${id}`)
      .then(response =&gt; response.json())
      .then(result =&gt; {
        setCurrentChannel(
          {
            room: result.data,
            users: result.data.attributes.users,
            messages: result.data.attributes.messages
          }
        )
      })
    };
  
    const subscribeToRoom = (event) =&gt; {
      const room_id = event.target.id
      user ? (this.postFirstMessage(room_id)) : (alert('You must be logged in to subscribe to a room.'))
    };
  
    const postFirstMessage = (roomId) =&gt; {
      window.history.pushState(null, null, `/rooms/${roomId}`)
      const message = {
        content: `${this.state.currentUser.attributes.username} has joined this room!`,
        user_id: this.state.user.id,
        channel_id: roomId
      }
      fetch(&quot;/messages&quot;, {
          method: &quot;POST&quot;,
          headers: {
              &quot;Content-Type&quot;: &quot;application/json&quot;,
              Accept: &quot;application/json&quot;
          },
          body: JSON.stringify({message: message})
      })
      .then(resp =&gt; resp.json())
      .then(result =&gt; {
      })
    };
  
      return (
        &lt;UserContext.Provider value={user, setUser}&gt;
          
        &lt;div className=&quot;App container py-3&quot;&gt;
        &lt;Navbar collapseOnSelect bg=&quot;light&quot; expand=&quot;md&quot; className=&quot;mb-3&quot;&gt;
          &lt;Navbar.Brand href=&quot;/&quot; className=&quot;font-weight-bold text-muted&quot;&gt;
            Chat
          &lt;/Navbar.Brand&gt;
          &lt;Navbar.Toggle /&gt;
          &lt;Navbar.Collapse className=&quot;justify-content-end&quot;&gt;
            &lt;Nav activeKey={window.location.pathname}&gt;
              {user ? (
                &lt;&gt;
                &lt;Navbar.Text&gt; Welcome, USER &lt;/Navbar.Text&gt;
                &lt;Nav.Item&gt;&lt;Nav.Link onClick={handleLogout}&gt;Logout&lt;/Nav.Link&gt;
                &lt;/Nav.Item&gt;
                &lt;/&gt;
              ) : (
                &lt;&gt;
                  &lt;LinkContainer to=&quot;/signup&quot;&gt;
                    &lt;Nav.Link&gt;Signup&lt;/Nav.Link&gt;
                  &lt;/LinkContainer&gt;
                  &lt;LinkContainer to=&quot;/login&quot;&gt;
                    &lt;Nav.Link&gt;Login&lt;/Nav.Link&gt;
                  &lt;/LinkContainer&gt;
                &lt;/&gt;
              )}
            &lt;/Nav&gt;
          &lt;/Navbar.Collapse&gt;
        &lt;/Navbar&gt;
        &lt;Switch&gt;
          &lt;Route exact path=&quot;/&quot;&gt;
            &lt;Home /&gt;
          &lt;/Route&gt;
          &lt;Route exact path=&quot;/login&quot;
          // props such as props.history
          // props.history.push used to redirection https://reactrouter.com/web/api/history
          render={ (props) =&gt; (&lt;Login
                      {...props}
                      handleLogin={handleLogin} /&gt;) } /&gt;
          &lt;Route exact path=&quot;/signup&quot;
            render={ (props) =&gt; (&lt;Signup
                      {...props} 
                      handleLogin={handleLogin} /&gt;) } /&gt;
          &lt;Route exact path='/rooms' 
            render={ (props) =&gt; (&lt;Rooms /&gt;) } /&gt;
          &lt;Route exact path='/rooms/:id' 
            render={ (props) =&gt; {
              return user ? (&lt;RoomShow {...props}
              cableApp={this.props.cableApp}
              getRoomData={this.getRoomData}
              updateApp={this.updateAppStateRoom}
              roomData={this.state.currentRoom}
              currentUser={this.state.user.data}
            /&gt;
            ) : (
              &lt;Redirect to='/rooms' /&gt;
            )
            }} /&gt;
        &lt;/Switch&gt;
      &lt;/div&gt;
      &lt;/UserContext.Provider&gt;
    );
  
  }
  
  export default App;
  </code></pre>
  <p>containers/Login.js</p>
  <pre><code>import &quot;./Login.css&quot;;
  import axios from 'axios'
  import React, { useState } from &quot;react&quot;;
  import { Link } from 'react-router-dom'
  import Form from &quot;react-bootstrap/Form&quot;;
  import Button from &quot;react-bootstrap/Button&quot;;
  import  UserContext  from '../context/UserContext'
  
  function Login(props){
    const [login, setLogin] = useState({username: null, password: null, errors: null})
  
    const handleChange = (event) =&gt; {
        const {name, value} = event.target
        setLogin({
          ...login,
          [name]: value
        })
      };
    
    const handleSubmit = (event) =&gt; {
      event.preventDefault()
      const {username, password} = login
      let user = {
        username: username,
        password: password
    }
    axios.post('/login', {user}, {withCredentials: true})
      .then(response =&gt; {
        if (response.data.logged_in) {
          props.handleLogin(response.data)
          redirect();
        } else {
          handleErrors();
          console.log('response errors:', response.data.errors)
          setLogin({
            ...login,
            errors: response.data.errors
          })
        }
      })
      .catch(error =&gt; {
        handleErrors();
        console.log('api errors:', error)
      })
    };
  
  
    const redirect = () =&gt; {
      props.history.push('/')
    }
  
    const handleErrors = () =&gt; {
    };
  
    return (
      &lt;div className=&quot;Login&quot;&gt;
      &lt;Form onSubmit={handleSubmit}&gt;
        &lt;Form.Group size=&quot;lg&quot; controlId=&quot;username&quot;&gt;
        &lt;Form.Label&gt;Username&lt;/Form.Label&gt;
        &lt;Form.Control
            autoFocus
            type=&quot;text&quot;
            name=&quot;username&quot;
            onChange={handleChange}
        /&gt;
        &lt;/Form.Group&gt;
        &lt;Form.Group size=&quot;lg&quot; controlId=&quot;password&quot;&gt;
        &lt;Form.Label&gt;Password&lt;/Form.Label&gt;
        &lt;Form.Control
            type=&quot;password&quot;
            name=&quot;password&quot;
            onChange={handleChange}
        /&gt;
        &lt;/Form.Group&gt;
        &lt;Button block size=&quot;lg&quot; type=&quot;submit&quot;&gt;
        Login
        &lt;/Button&gt;
        &lt;div&gt;
            or &lt;Link to='/signup'&gt;sign up&lt;/Link&gt;
        &lt;/div&gt;
      &lt;/Form&gt;
      &lt;/div&gt;
    );
  }
  
  export default Login;
  </code></pre>
  <p>containers/Home.js</p>
  <pre><code>import React from &quot;react&quot;;
  import &quot;./Home.css&quot;;
  
  export default function Home() {
    return (
      &lt;div className=&quot;Home&quot;&gt;
        &lt;div className=&quot;lander&quot;&gt;
          &lt;h1&gt;Chat&lt;/h1&gt;
          &lt;p className=&quot;text-muted&quot;&gt;A simple chat application&lt;/p&gt;
        &lt;/div&gt;
      &lt;/div&gt;
    );
  }
  </code></pre>
  <p>context/UserContext.js</p>
  <pre><code>import React from 'react'
  
  const UserContext = React.createContext(null)
  
  export default UserContext
  </code></pre>
  <p>note:<br />
  I previously used <code>&lt;UserContext.Consumer/&gt;</code> over multiple children but omitted because of the error</p>
  <pre><code>TypeError: render is not a function
  </code></pre>