CodingNic

Persistence

Load Tasks When the App Starts

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:

javascript
const [tasks, setTasks] = useState(starterTasks);

change it to:

javascript
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:

javascript
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.