CLOSE
Did you know you can pass a function to useState in React? Here's how it works.
Instead of passing a value directly to useState, you can pass a function that returns a value. The returned value is used as the initial state. This approach is particularly useful when the initial state needs to be computed or read from memory, such as local storage.
Here's an example:
import { useState } from "react";
const [cart, setCart] = useState(() => {
const savedCart = localStorage.getItem("cart");
return savedCart ? JSON.parse(savedCart) : [];
});
Happy coding!