CodeBlanks Logo Icon CodeBlanks

Persistent theme

Learn persistent theme with AsyncStorage.

Persistent theme

A persistent theme keeps the user's chosen theme even after closing and reopening the app. For this, the preference is written to AsyncStorage and read from it on launch. This way the user sees the last chosen theme on every launch.

To save: AsyncStorage.setItem('theme', theme.name). To read: an effect calls AsyncStorage.getItem('theme') on launch; when the value comes back, setTheme applies it.

Loading on launch

To load the theme on launch, useEffect is used. On mount, AsyncStorage.getItem('theme') is called; the returned value is applied with setTheme. This effect runs only once. This makes the preference ready at launch.

When the user changes the theme, you save the new value with AsyncStorage.setItem. So the next launch restores the last preference.

Practice Save the theme on change

Add a useEffect that calls AsyncStorage.setItem('theme', theme.name) whenever theme changes. Put theme in the dependency array. The theme state and the AsyncStorage import are defined.

Starter code

App.js
import React, { useState } from 'react';
import { View } from 'react-native';
import AsyncStorage from '@react-native-async-storage/async-storage';

const light = { name: 'light', background: '#fff' };
const dark = { name: 'dark', background: '#000' };

export default function App() {
  const [theme, setTheme] = useState(light);
  // Save to AsyncStorage when theme changes
  return <View style={{ backgroundColor: theme.background }} />;
}

Sample solution

App.js
import React, { useEffect, useState } from 'react';
import { View } from 'react-native';
import AsyncStorage from '@react-native-async-storage/async-storage';

const light = { name: 'light', background: '#fff' };
const dark = { name: 'dark', background: '#000' };

export default function App() {
  const [theme, setTheme] = useState(light);
  useEffect(() => {
    AsyncStorage.setItem('theme', theme.name);
  }, [theme]);
  return <View style={{ backgroundColor: theme.background }} />;
}

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 AsyncStorage import

Question
import ____ from '@react-native-async-storage/async-storage';
Answer
import AsyncStorage from '@react-native-async-storage/async-storage';

Explanation: AsyncStorage is the persistent storage library.

2 Match the persistent theme concepts

Term Meaning
AsyncStorage Storage
setItem Saves
getItem Reads
theme Preference value

3 What does a persistent theme provide?

  • Faster rendering
  • Keeping the preference Correct answer
  • Color generation
  • Navigation

Explanation: A persistent theme keeps the preference even after closing.

All lessons in Intermediate