Persistence
15 min read
Load Tasks When the App Starts
Load Tasks When the App Starts
Now use the reader when App creates its initial state.
If you currently have:
const [tasks, setTasks] = useState(starterTasks);
change it to:
const [tasks, setTasks] = useState(loadTasks);
React can accept a function as the initial-state argument. That lets the initial value come from localStorage instead of always using the sample array.
A small improvement for the first render
If you prefer to make the intent explicit, use a lazy initializer:
const [tasks, setTasks] = useState(() => loadTasks());
The function is used to calculate the initial value rather than treating the result as a value that must be calculated on every render.
Checkpoint
Open the browser’s developer tools and inspect Application/Storage if your browser provides that panel. If there is no saved value yet, the board should still use the sample tasks.