<?xml version="1.0" encoding="UTF-8"?>
<rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/"
    xmlns:atom="http://www.w3.org/2005/Atom" xmlns:media="http://search.yahoo.com/mrss/" version="2.0">
    <channel>
        
        <title>
            <![CDATA[ keep a user signed in - freeCodeCamp.org ]]>
        </title>
        <description>
            <![CDATA[ Browse thousands of programming tutorials written by experts. Learn Web Development, Data Science, DevOps, Security, and get developer career advice. ]]>
        </description>
        <link>https://www.freecodecamp.org/news/</link>
        <image>
            <url>https://cdn.freecodecamp.org/universal/favicons/favicon.png</url>
            <title>
                <![CDATA[ keep a user signed in - freeCodeCamp.org ]]>
            </title>
            <link>https://www.freecodecamp.org/news/</link>
        </image>
        <generator>Eleventy</generator>
        <lastBuildDate>Sun, 10 May 2026 16:29:03 +0000</lastBuildDate>
        <atom:link href="https://www.freecodecamp.org/news/tag/keep-a-user-signed-in/rss.xml" rel="self" type="application/rss+xml" />
        <ttl>60</ttl>
        
            <item>
                <title>
                    <![CDATA[ How to Persist a Logged-in User in React ]]>
                </title>
                <description>
                    <![CDATA[ By Adebola Adeniran If you run a quick Google search for persisting a logged-in user in React (or keeping a user logged in in React), you don't get a lot of straightforward results. There aren't really any easy to follow examples on how to achieve th... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/how-to-persist-a-logged-in-user-in-react/</link>
                <guid isPermaLink="false">66d45d5fc17d4b8ace5b9eb2</guid>
                
                    <category>
                        <![CDATA[ keep a user signed in ]]>
                    </category>
                
                    <category>
                        <![CDATA[ localstorage ]]>
                    </category>
                
                    <category>
                        <![CDATA[ login forms ]]>
                    </category>
                
                    <category>
                        <![CDATA[ React ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ freeCodeCamp ]]>
                </dc:creator>
                <pubDate>Mon, 15 Jun 2020 21:39:17 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2020/06/Slice-3-1-.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>By Adebola Adeniran</p>
<p>If you run a quick Google search for persisting a logged-in user in React (or keeping a user logged in in React), you don't get a lot of straightforward results. There aren't really any easy to follow examples on how to achieve this. So I decided I had to write that simple guide.</p>
<p>You may have done a search on this and saw the word <strong>localStorage</strong> being thrown around. Yes, we'll be using <strong>localStorage</strong> but I'm going to show you exactly how it's done. </p>
<h2 id="heading-some-notes-on-localstorage">Some notes on localStorage.</h2>
<ol>
<li><strong>localStorage</strong> is the browser's database. The data is stored inside your browser in your computer's memory.</li>
<li><strong>localStorage</strong> is specific to an origin. In other words, the localStorage for one website cannot be accessed by another.</li>
</ol>
<h2 id="heading-initial-setup">Initial setup</h2>
<p>Let's get started. I've deployed a simple express server to Heroku for use in testing this application.</p>
<ol>
<li>Create a new React application and head into the <strong><code>&lt;App /&gt;</code></strong> component. </li>
<li>Install axios using <code>npm install axios</code> and import it inside <strong><code>&lt;App /&gt;</code></strong></li>
<li>Next, create a simple login form that accepts a username and password. </li>
</ol>
<pre><code><span class="hljs-keyword">import</span> React, { useState } <span class="hljs-keyword">from</span> <span class="hljs-string">"react"</span>;
<span class="hljs-keyword">import</span> axios <span class="hljs-keyword">from</span> <span class="hljs-string">"axios"</span>;

<span class="hljs-keyword">const</span> App = <span class="hljs-function">() =&gt;</span> {
  <span class="hljs-keyword">const</span> [username, setUsername] = useState(<span class="hljs-string">""</span>);
  <span class="hljs-keyword">const</span> [password, setPassword] = useState(<span class="hljs-string">""</span>);
  <span class="hljs-keyword">const</span> [user, setUser] = useState()

  <span class="hljs-keyword">const</span> handleSubmit = <span class="hljs-keyword">async</span> e =&gt; {

  };

<span class="hljs-comment">// if there's a user show the message below</span>
  <span class="hljs-keyword">if</span> (user) {
    <span class="hljs-keyword">return</span> <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">div</span>&gt;</span>{user.name} is loggged in<span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span></span>;
  }

  <span class="hljs-comment">// if there's no user, show the login form</span>
  <span class="hljs-keyword">return</span> (
    <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">form</span> <span class="hljs-attr">onSubmit</span>=<span class="hljs-string">{handleSubmit}</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">label</span> <span class="hljs-attr">htmlFor</span>=<span class="hljs-string">"username"</span>&gt;</span>Username: <span class="hljs-tag">&lt;/<span class="hljs-name">label</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">input</span>
        <span class="hljs-attr">type</span>=<span class="hljs-string">"text"</span>
        <span class="hljs-attr">value</span>=<span class="hljs-string">{username}</span>
        <span class="hljs-attr">placeholder</span>=<span class="hljs-string">"enter a username"</span>
        <span class="hljs-attr">onChange</span>=<span class="hljs-string">{({</span> <span class="hljs-attr">target</span> }) =&gt;</span> setUsername(target.value)}
      /&gt;
      <span class="hljs-tag">&lt;<span class="hljs-name">div</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">label</span> <span class="hljs-attr">htmlFor</span>=<span class="hljs-string">"password"</span>&gt;</span>password: <span class="hljs-tag">&lt;/<span class="hljs-name">label</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">input</span>
          <span class="hljs-attr">type</span>=<span class="hljs-string">"password"</span>
          <span class="hljs-attr">value</span>=<span class="hljs-string">{password}</span>
          <span class="hljs-attr">placeholder</span>=<span class="hljs-string">"enter a password"</span>
          <span class="hljs-attr">onChange</span>=<span class="hljs-string">{({</span> <span class="hljs-attr">target</span> }) =&gt;</span> setPassword(target.value)}
        /&gt;
      <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">button</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"submit"</span>&gt;</span>Login<span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">form</span>&gt;</span></span>
  );
};

<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> App;
</code></pre><p>As you can see, we've defined an asynchronous <strong>handleSubmit</strong> function to process the login request. We've also defined a conditional that displays a <strong>user.name is logged in</strong> message if we have a user, and the login form if we do not have a user.</p>
<p>Next, let's complete the function. This function will work in the following steps:</p>
<ol>
<li>Send the login details to the server.</li>
<li>If the request is successful (async-await), store the user information in                    localStorage and set the State of the User.</li>
</ol>
<h2 id="heading-handle-the-login-event">Handle the login event</h2>
<p>Let's define the <strong>handleSubmit</strong> event handler.</p>
<pre><code>  <span class="hljs-keyword">const</span> handleSubmit = <span class="hljs-keyword">async</span> e =&gt; {
    e.preventDefault();
    <span class="hljs-keyword">const</span> user = { username, password };
    <span class="hljs-comment">// send the username and password to the server</span>
    <span class="hljs-keyword">const</span> response = <span class="hljs-keyword">await</span> axios.post(
      <span class="hljs-string">"http://blogservice.herokuapp.com/api/login"</span>,
      user
    );
    <span class="hljs-comment">// set the state of the user</span>
    setUser(response.data)
    <span class="hljs-comment">// store the user in localStorage</span>
    <span class="hljs-built_in">localStorage</span>.setItem(<span class="hljs-string">'user'</span>, response.data)
    <span class="hljs-built_in">console</span>.log(response.data)
  };
</code></pre><p>Note: Use a <strong>tryCatch</strong> block to handle errors in async functions.</p>
<p>Now that our function is done, you can run <strong>npm start</strong> to test out your app. Login with the <strong>username</strong>: user2, <strong>password</strong>: password.</p>
<p>You should receive the following as a response. The <em>userId</em>, <em>token</em> and <em>username</em></p>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/06/image-52.png" alt="Image" width="600" height="400" loading="lazy"></p>
<h2 id="heading-check-if-a-user-has-previously-logged-in">Check if a user has previously logged in</h2>
<p>Next, we want a way to check if there's a user logged in each time the App loads. For that, we use the useEffect hook. </p>
<pre><code> useEffect(<span class="hljs-function">() =&gt;</span> {
    <span class="hljs-keyword">const</span> loggedInUser = <span class="hljs-built_in">localStorage</span>.getItem(<span class="hljs-string">"user"</span>);
    <span class="hljs-keyword">if</span> (loggedInUser) {
      <span class="hljs-keyword">const</span> foundUser = <span class="hljs-built_in">JSON</span>.parse(loggedInUser);
      setUser(foundUser);
    }
  }, []);
</code></pre><p>Remember to use an empty dependency array in your useEffect hook so that it checks if there's a logged in user the first time the app loads.</p>
<p>Now our app should work perfectly. We get the page below after a user has logged in for the first time and their details are stored. If you refresh the page, you'll see that our user stays logged in and the logged in page continues to show.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/06/image-55.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>As a bonus tip, here's how to implement logout.</p>
<h2 id="heading-implementing-logout-functionality">Implementing Logout functionality</h2>
<p>For logging out, we simply empty the user state and remove the user from localStorage. </p>
<p>Let's implement that. </p>
<p>First, we create a logout button</p>
<pre><code>&lt;button onClick={handleLogout}&gt;logout&lt;/button&gt;
</code></pre><p>Then, we create the logout function.</p>
<pre><code><span class="hljs-keyword">const</span> handleLogout = <span class="hljs-function">() =&gt;</span> {
    setUser({});
    setUsername(<span class="hljs-string">""</span>);
    setPassword(<span class="hljs-string">""</span>);
    <span class="hljs-built_in">localStorage</span>.clear();
  };
</code></pre><p>And that's it, we're done.</p>
<p>Here's a link to the full <a target="_blank" href="https://gist.github.com/onedebos/bbf7cd4634bce53103c1cfefa6164637">gist</a> on GitHub. You can follow me there for more updates.</p>
 ]]>
                </content:encoded>
            </item>
        
    </channel>
</rss>
