We have a counter that changes when we click a button. We want to store the counter value in local storage so that when we refresh the page, the counter value is not lost.
Here is the updateCounter
function from the previous task:
We want to log the counter value whenever it changes. We can add a console.log
statement to log the counter value:
This will work in most cases, but there is a catch. The setCount
function will not update the count
value immediately. The setCount
function will run after the component re-renders, and the count
value will be updated then. This can lead to incorrect logging of the counter value. This is because the console.log
statement will log the current value of count
before the component re-renders, not the updated value. This is a common pitfall when working with React state, especially when updating other state values based on the current state value.
To log the correct counter value, we can use the useEffect
hook to log the counter value after the component re-renders:
In the above code, we have added a useEffect
hook that logs the counter value whenever it changes. The useEffect
hook runs after the component re-renders and logs the updated counter value.
Now, whenever the counter value changes, it will be logged to the console. Try clicking the buttons and see the counter value being logged to the console. Notice there is an initial log “Count updated: 0” when the component is first rendered. (There is actually two logs, one for the initial render but this is due to using React.StrictMode
which renders the component twice in development mode.)
useEffect
HookThe useEffect
hook is used to perform side effects in function components. Side effects include anything that happens outside the components rendering, such as data fetching, subscriptions, manually changing the DOM, or in this case, logging the counter value.
The useEffect
hook takes two arguments: a function and an array of dependencies.
The function passed to useEffect
is called after the component is rendered. The function can perform any side effects, such as logging the counter value in this case.
The array of dependencies is used to specify when the effect should run. If the array of dependencies is empty, the effect runs only once after the initial render. If the array of dependencies contains values, the effect runs whenever any of the values in the array change. For example, in this case, the effect runs whenever the count
value changes.
One of the common use cases of the useEffect
hook is to interact with APIs, such as fetching data from a server, or storing data to it. We are not going to use an API in this task, but we will use local storage to store the counter value.
Local storage is a way to store data in the browser. It is a key-value pair storage system. The data stored in local storage is not lost when the browser is closed. It is stored until the user clears the browser cache or deletes the data.
Local storage is supported by all modern browsers. There is a simple API to interact with local storage. The data stored in local storage is stored as strings. So, we need to convert the data to a string before storing it and convert it back to the original data type when retrieving it.
Here is an example of how to store data in local storage:
The localStorage
is a global object that provides methods to interact with local storage. The localStorage.setItem
method is used to store data in local storage. It takes two arguments: the key and the value. The localStorage.getItem
method is used to retrieve data from local storage. It takes the key as an argument and returns the value stored in local storage.
It is common to store data in local storage when building web applications. For example, you can store user preferences, settings, or any other data that needs to be persisted across sessions. In the next step, we will store the counter value in local storage.
We want to store the counter value in local storage whenever it changes. Update the useEffect
hook to store the counter value in local storage instead of logging it:
Now run the application and click the buttons to change the counter value. The counter value will be stored in local storage whenever it changes. You can verify this by opening the browser developer tools, going to the “Application” tab, and selecting “Local Storage”. You should see the “count” key with the counter value stored in local storage.
We have stored the counter value in local storage. The benefit of storing the counter value in local storage is that it persists even when the browser is closed. Now we want to retrieve the counter value from local storage when the component is first rendered. We can do this by reading the counter value from local storage when we initialize the count
state:
In the above code, we are using the useState
hook with a function as the initial state. The function reads the counter value from local storage using localStorage.getItem("count")
. If the counter value is stored in local storage, it is parsed to an integer using parseInt(storedCount, 10)
and returned as the initial state. If the counter value is not stored in local storage, the initial state is set to 0
.
Now, when the component is first rendered, the counter value is retrieved from local storage and displayed. Try refreshing the page, and you will see the counter value is loaded from local storage.
In this task, we learned how to store the counter value in local storage. We used the localStorage
API to store and retrieve the counter value. Storing the counter value in local storage ensures that the counter value persists even when the browser is closed. This is useful for storing user preferences, settings, or any other data that needs to be persisted across sessions.
We also learned how to use the useEffect
hook to perform side effects in function components. The useEffect
hook is used to interact with APIs, perform data fetching, or store data in local storage. By using the useEffect
hook, we can ensure that the side effects are performed after the component is rendered.