Using Local Storage in React.
Published: 2020-10-17 08:38:38

Local storage enables the user to persist items within the browser window so that even when the user leaves the webpage, their data is stored temporarily for the duration of the visit. It often offers a pretty straightforward approach to bypassing the need for a database when building simpler applications.

Let's take a look at a simple React Application whose function is to generate a single random token and save to local storage every time a user clicks on a 'Generate token' button.

In our root folder, we have an `index.js` file which renders our components to the page.

```javascript
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App'

ReactDOM.render(<App/>, document.getElementById('root'))
```

Next, we have a `token.js` file which contains an array of random words and a function that loops through the array to display a random word each time the button is clicked. 

```javascript
const tokens = [
    "abate", "abbas", "abbe", "abbey", "abbot", "abbott", "abc", "abe", "abed", "abel", "abet", "abide", "abject", "ablaze", "able", "abner", "abo", "abode", "abort", "about", "above", "image", "imbue", "imp", "impel", "import", "impute", "inane", "inapt", "inc", "inca", "incest", "inch", "incur", "index", "india", "indies", "indy", "inept", "inert", "infect", "infer", "infima", "infix", "infra", "ingot", "inhere", "injun", "ink", "inlay", "inlet", "inman", "inn", "inner", "input", "insect", "yip", "ymca", "yodel", "yoder", "yoga", "yogi", "yoke", "yokel", "yolk", "yon", "yond", "yore", "york", "yost", "you", "young", "your", "youth", "yow", "yucca", "yuck", "yuh", "yuki", "yukon", "yule", "yves", "ywca", "yyy", "yyyy", "zag", "zaire", "zan", "zap", "zazen", "zeal", "zealot", "zebra", "zeiss", "zen", "zero", "zest", "zesty", "zeta", "zeus", "zig", "zilch", "zinc", "zing", "zion"
];

const generateToken = () => {
    let random = Math.floor(Math.random() * tokens.length)
    let randomWord = tokens[random]
    return randomWord;  
};

export default generateToken;
```

Finally we have our `App.js` component where the bulk of our logic will reside.

```javascript
import React from 'react';
import {useState, useEffect} from 'react';
import generateToken from './token';

const App = () => {
    const [token, setToken] = useState('')
    useEffect(() => {
        localStorage.setItem('storedToken', token)
    })

    const handleClick = () => {
       setToken(generateToken())  
    }

    return (
        <div>
            <h1>Using LocalStorage in React</h1>
            <button onClick= {handleClick}>Generate New Token</button>
            <div>{token}</div>
        </div>
    )
}

export default App
```

We import the generateToken function from 'token.js' and the {useState and useEffect} hooks from 'react';

Within our App component, we first initialize our state to an empty string .

```javascript
 const [token, setToken] = useState('')
```
Now within the useEffect hook, we use `localStorage.setItem` which takes in two parameters. A key, which we can name anything we want, but we will name `storedToken` and a second parameter which is what we want to store within the localStorage. Here we want to store the newly generated token whenever the button is clicked which we have stored within our `token` state.

Inside our return statement, we add our button and attach an onClick event listener that calls on a function `handleClick` which is invoked whenever the button is clicked. This function is responsible for updating our state with the new random token generated on button click.

```javascript
const handleClick = () => {
        setToken(generateToken())  
    }
```

To confirm that your newly generated token has been saved to localStorage, right-click and inspect the page
Go to Application, and you will see a key: value pair of 'storeToken' and whichever random token is generated.

Your app should look this way now.


![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/ufxcm8uwthv89sbu7zpz.png)