Utilizing localStorage, useEffect, and useRef is crucial for the solution. The key logic is implemented within the useEffect hook, as it handles all the necessary operations when the component mounts. Check out this working example.
- Start by initializing an absolute number using useRef
- Attempt to retrieve a value from localStorage; if it's empty, set a default value. This is also where we check the array index.
- The next time around, skip the check and increment the obtained value and absolute number.
- Finally, send the result to both state and localStorage
App.js
import { useState, useEffect, useRef } from "react";
export default function App() {
const img1 = "https://dummyimage.com/400x200/a648a6/e3e4e8.png";
const img2 = "https://dummyimage.com/400x200/4e49a6/e3e4e8.png";
const img3 = "https://dummyimage.com/400x200/077d32/e3e4e8.png";
let [lsNum, setLsNum] = useState(0);
// Initialize an absolute number with '1'
let count = useRef(1);
const list = [img1, img2, img3];
useEffect(() => {
// Retrieve the value from localStorage and convert to a number
const lS = Number(localStorage.getItem("image"));
// Conditional check: If localStorage contains number 2 or more, reset it to 0
if (lS >= 2) {
localStorage.setItem("image", 0);
return;
}
// Increment the absolute number using the value from localStorage
count.current = count.current + lS;
// Update the state with the result
setLsNum(count.current);
// Store the resulting number in localStorage
localStorage.setItem("image", count.current);
}, []);
const css = {
height: "200px",
width: "400px",
display: "block",
backgroundImage: `url(${list[lsNum]})`, // dynamically change image based on index
backgroundPosition: "center",
backgroundSize: "cover",
border: "1px solid red"
};
return (
<div className="App">
<div style={css}></div>
</div>
);
}