How to use localStorage with React

How to use localStorage with React

In this article to showcase the usage of session storage and local storage in React to persist your local state, to cache it for browser reloads,

In this article to showcase the usage of session storage and local storage in React to persist your local state, to cache it for browser reloads,

The heart of every React application is its state. Components can have their own internal state and, believe me, despite being simple, you can do a lot of cool stuff with React’s state mechanism. But, let’s say you’re creating a nice app and, at some point, you need to save some user preference locally in the browser or even persist the complete state for one or more of your components. That is, you want to know: How to use localStorage in a React application? Well, setState won’t do this for you, but don’t worry, it’s really simple. Just keep reading!

Web Storage API

Web Storage is an API to store data in the browser, being a significant improvement compared to its predecessor, cookies. It started as a HTML5 API, later evolving to become an independent specification. It’s natively supported by virtually every browser in use today and even some legacy ones, like IE8. Web Storage is implemented in two different ways in browsers: localStorage (a persistent storage, which can be compared to persistent cookies) and sessionStorage (a storage that persists for duration of the session, comparable to session cookies). Though this article focus on localStorage, you can also apply the same principles when using sessionStorage.

Our example component

We need a component to play around with. Well, I think a sign-in page with a “Remember me” option is a perfect fit. For simplicity’s sake, we won’t include a password field, since it shouldn’t be persisted. Let’s check out its render method:

render() {
  return (
    <form onSubmit={this.handleFormSubmit}>
      <label>
        User: <input name="user" value={this.state.user} onChange={this.handleChange}/>
      </label>
      <label>
        <input name="rememberMe" checked={this.state.rememberMe} onChange={this.handleChange} type="checkbox"/> Remember me
      </label>
      <button type="submit">Sign In</button>
    </form>
  );
}

As you can see, it’s a pretty simple form, with two inputs and a button. The code needed to handle its state is equally easy to understand:

export default class SignIn extends Component {
  state = {
    user: '',
    rememberMe: false
  };

  handleChange = (event) => {
    const input = event.target;
    const value = input.type === 'checkbox' ? input.checked : input.value;

    this.setState({ [input.name]: value });
  };

  handleFormSubmit = () => {};

  render() { /*...*/ }
}

In the above piece of code, we’re using the setState method to keep the component’s state up-to-date every time a change occurs in our form. If you run the project, here’s what you’ll get:

Note: I know its appearance is raw, but for the purpose of this article, let’s turn a blind eye to this. =)

If you fill the User input, then check the “Remember me” option and finally click the “Sign in” button, you’ll notice that the page is reloaded and the form becomes empty again:

This behavior is completely normal. Now, we will learn how to use localStorage with React and make this form work as expected.

Step 1: Saving data in the localStorage

We have two things to be stored in our example:

  1. The value of the “Remember me” option
  2. The user name (only if the “Remember me” option is checked)

The perfect place to persist these values is in the handleFormSubmit method:

handleFormSubmit = () => {
  const { user, rememberMe } = this.state;
  localStorage.setItem('rememberMe', rememberMe);
  localStorage.setItem('user', rememberMe ? user : '');
};

So, what is really happening in this method?

  • First, we use destructuring assignment to initialize two variables
  • Then, we’re calling the localStorage.setItem method to store the value of the “Remember me” option
  • Finally, we persist the user name too, but only if the “Remember me” option is set to true

And this is what we have so far:

Ok, we’re halfway there. Now we need to get back those values to rehydrate our component.

Step 2: Retrieving data from the localStorage

We’ll put our data retrieval logic in the componentDidMount lifecycle method, but you can safely put it in your constructor, if you want to, since its purpose is to set the initial state of our component.

Note: You can’t call setState before the component is mounted, so, if you prefer the constructor approach, just set the state property directly instead. As for me, I like to keep my constructors as clean as possible, but it’s a matter of personal preference.

componentDidMount() {
  const rememberMe = localStorage.getItem('rememberMe') === 'true';
  const user = rememberMe ? localStorage.getItem('user') : '';
  this.setState({ user, rememberMe });
}

Let’s understand it better:

  • First, we use destructuring assignment to initialize two variables
  • Then, we’re calling the localStorage.setItem method to store the value of the “Remember me” option
  • Finally, we persist the user name too, but only if the “Remember me” option is set to true

And here’s the magic happening:

Great! Everything worked as expected. Take a look at the final code, here.

A final tip

As I mentioned above, localStorage can only store data as string. If you’re dealing with just a few persisted values, this is no big deal. But if you intend to make a significant use of localStorage throughout your application, I totally recommend you to pick a library to make it easier to save and retrieve data and to abstract things like stringification and parsing. An excellent and battle-tested option is Store.js. That’s my personal recommendation. =)

Conclusion

  • First, we use destructuring assignment to initialize two variables
  • Then, we’re calling the localStorage.setItem method to store the value of the “Remember me” option
  • Finally, we persist the user name too, but only if the “Remember me” option is set to true

URLs and Webpack in Reactjs

URLs and Webpack in Reactjs

URLs and Webpack in Reactjs - I am still a newbie in ReactJS. I've been following series of tutorials and articles on the framework and decided to start putting what I've learnt so far into practice.

My website, dillionmegida.com was built with PHP. You could check it out as I highly appreciate reviews. I'm though aspiring to be a full-stack javascript developer so I'm in some way trying to depart from PHP :)

I decided to replicate my homepage using React and to broaden my skills in using components.

It was going quite successful until I tried using an <img> JSX element. I used it like;

import React from 'react'
 
let dpStyle = {
    // Some styles
}
 
let Profilepic = () => (
    <div className={dpStyle}>
        <img src='../img/deee.jpeg' alt='My profile picture'/>
    </div>
)
export default Profilepic;

The img folder was a sub-directory of the src folder.

My aim here was to have my profile picture as a component with some styling to be used on my homepage and any other desired page. The src for the img tag was not been used appropriately as my image was not displayed.

I paused to think of the problem, inspected my page and discovered the src displayed there was exactly as I inputted it. So silly of me :( I made some researches which helped me remember that most attributes of JSX element are not as mostly used with HTML, but have to be enclosed in curly braces.

import React from 'react'
 
let dpStyle = {
    // Some styles
}
 
let Profilepic = () => (
    <div className={dpStyle}>
        <img src={'../img/deee.jpeg'} alt='My profile picture'/>
    </div>
)
export default Profilepic;

I tried rendering the page again and my image was still not displayed.

Funny enough, I quickly thought of a trick (for the first time);

...
import Dp from '../img/deee.jpeg'
...
let Profilepic = () => (
    <div className={dpStyle}>
        <img src={Dp} alt='My profile picture'/>
    </div>
)

To my amazement, it worked. I was excited and at the same time sad, with feeling of little guilt. I didn't know why. lol. I said to myself, 'I am not doing the right thing :(' and also asked myself, 'Is react as crazy as this?'

I headed back to google to make some more research and got to discover that the webpack that React (create-react-app) automatically installed had been configured to use the public folder (at the same level with src folder) for relative URLs (such as my image URL).

Using ...<img src={'../img/deee.jpeg'} />..., React was actually checking the public folder for the image sub-directory which it couldn't find.

Solution

1. Change the location of the image folder

I changed the location of the image folder making it a sub-directory under the public directory and it worked as expected.

2. Use the require keyword

Just as the import keyword is used for relative URLs, the require keyword does same. So, I was able to do this;

import React from 'react'
 
let dpStyle = {
    // Some styles
}
 
let Profilepic = () => (
    <div className={dpStyle}>
        <img src={require('../img/deee.jpeg')} alt='My profile picture'/>
    </div>
)
export default Profilepic;

and in the other pages where the Profilepic component was required and used, my image displayed perfectly. :D

Like I said, I am still a newbie at ReactJS but I hope this little experience would be helpful for you too. There are other super powers of webpacks too which I would still be learning. Please do share in the comment section corrections on this article and also helpful Tips.

I'll be documenting my experience in my ReactJS journey as much as I can. Stay tuned and thanks for reading.

Originally published by Megida Dillion at dillion.hashnode.dev

=======================================================

Thanks for reading :heart: If you liked this post, share it with all of your programming buddies! Follow me on Facebook | Twitter

Learn More

☞ Understanding TypeScript

☞ Typescript Masterclass & FREE E-Book

☞ React - The Complete Guide (incl Hooks, React Router, Redux)

☞ Modern React with Redux [2019 Update]

☞ The Complete React Developer Course (w/ Hooks and Redux)

☞ React JS Web Development - The Essentials Bootcamp

☞ React JS, Angular & Vue JS - Quickstart & Comparison

☞ The Complete React Js & Redux Course - Build Modern Web Apps

☞ React JS and Redux Bootcamp - Master React Web Development


Why ReactJS is technically superior?

Reactjs provides you with a high UI design and learning API, and it works on the base of a JavaScript framework, serves you a great mechanism V-DOM and provides you swift updates as well. It helps in synchronization for re-render the complete site on every alteration.

Reactjs provides you with a high UI design and learning API, and it works on the base of a JavaScript framework, serves you a great mechanism V-DOM and provides you swift updates as well. It helps in synchronization for re-render the complete site on every alteration.