Listing 16-8: Reading localStorage Data in Clicker
0
import {useState,useEffect} from 'react';
import './style.css';
function Clicker3(){
const [count,setCount] = useState(Number(localStorage.getItem('counter')) || 0);
const incrementCount = ()=>{
setCount((prev)=>prev+1);
}
useEffect(()=>{
localStorage.setItem('counter',count);
},[count]);
return(
<div className="container">
<h1 className="current-count">{count}</h1>
<button className="increment-button"
onClick={incrementCount}>+</button>
</div>
)
}
export default Clicker3;
Download the examples, report issues, and ask/answer questions in the discussion area by visiting the book's github page. All of the code for the book is also available on codesandbox.io for you to play around with.
ReactJS Foundations is published by John Wiley and Sons, Inc and is available in paperback and eBook.