0Pricing
React Native Academy · 강의

영구 설정 화면 만들기

알림과 다크 모드를 전환할 수 있는 설정 화면을 만들고 각 설정을 AsyncStorage에 저장하며 앱 시작 시 환경설정을 복원합니다.

영구 설정 화면 만들기은(는) CoddyKit의 무료 React Native Academy 강의입니다. 이것은 4개 중 3번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 AI 튜터와 함께 브라우저에서 직접 실습할 수 있습니다. 이 강의는 React Native Academy 학습 경로의 일부이며, 진행 상황이 웹과 CoddyKit 앱에 동기화됩니다. React Native Academy 강의에는 총 4개의 강의가 포함되어 있습니다.

이 강의의 일부는 아직 번역되지 않았으며 영어로 표시됩니다.

What a Persistent Settings Screen Does

A persistent settings screen lets users configure app preferences — such as dark mode, notification preferences, or language — and have those preferences survive app restarts. The settings are saved to AsyncStorage when changed and loaded back on startup. This is one of the most common patterns in any production React Native app.

Defining the Settings State

Start by defining a TypeScript interface for your settings object and a DEFAULT_SETTINGS constant used when no saved settings exist (first launch). Keeping defaults in a constant makes it easy to fall back safely and to reference the initial shape in type guards and migration logic.

interface Settings {
  darkMode: boolean;
  notificationsEnabled: boolean;
  fontSize: 'small' | 'medium' | 'large';
}

const DEFAULT_SETTINGS: Settings = {
  darkMode: false,
  notificationsEnabled: true,
  fontSize: 'medium',
};

const SETTINGS_KEY = 'app_settings';

Loading Settings on Screen Mount

In a useEffect with an empty dependency array, read the settings from AsyncStorage, parse the JSON, and place the result in component state. Show an ActivityIndicator while loading so the user does not see a momentary flash of default values before the real settings appear.

const [settings, setSettings] = React.useState<Settings>(DEFAULT_SETTINGS);
const [loading, setLoading] = React.useState(true);

useEffect(() => {
  async function loadSettings() {
    const json = await AsyncStorage.getItem(SETTINGS_KEY);
    if (json) {
      setSettings({ ...DEFAULT_SETTINGS, ...JSON.parse(json) });
    }
    setLoading(false);
  }
  loadSettings();
}, []);

Saving Settings When They Change

Create a helper function that merges the new setting into the current settings object and writes the result to AsyncStorage. Call this function from each UI control's change handler so settings are saved immediately after every user interaction. There is no need for a separate 'Save' button for a settings screen.

async function updateSetting<K extends keyof Settings>(key: K, value: Settings[K]) {
  const updated = { ...settings, [key]: value };
  setSettings(updated);
  await AsyncStorage.setItem(SETTINGS_KEY, JSON.stringify(updated));
}

Rendering the Dark Mode Toggle

Use React Native's Switch component for boolean settings. Bind its value prop to the state and call updateSetting in onValueChange. The UI updates instantly via state while AsyncStorage saves in the background, giving a responsive feel without waiting for the write to complete.

<View style={styles.row}>
  <Text style={styles.label}>Dark Mode</Text>
  <Switch
    value={settings.darkMode}
    onValueChange={(value) => updateSetting('darkMode', value)}
    trackColor={{ false: '#ccc', true: '#6200ee' }}
    thumbColor={settings.darkMode ? '#fff' : '#f4f3f4'}
  />
</View>

Rendering a Notification Toggle

Add a second Switch row for the notifications setting following the same pattern. Reusing the same updateSetting helper keeps the code DRY — you only change the key argument to target a different setting. This pattern scales to any number of boolean settings without duplicating save logic.

<View style={styles.row}>
  <Text style={styles.label}>Notifications</Text>
  <Switch
    value={settings.notificationsEnabled}
    onValueChange={(value) => updateSetting('notificationsEnabled', value)}
  />
</View>

Font Size Picker with Pressable Options

For an enum setting like font size, render a row of Pressable buttons, one for each option. Highlight the currently selected option with a different background color. Tapping a button calls updateSetting with the new value. This creates a compact, accessible selection control without a full dropdown.

const fontSizes: Settings['fontSize'][] = ['small', 'medium', 'large'];

<View style={styles.row}>
  <Text style={styles.label}>Font Size</Text>
  <View style={styles.optionRow}>
    {fontSizes.map((size) => (
      <Pressable
        key={size}
        onPress={() => updateSetting('fontSize', size)}
        style={[
          styles.option,
          settings.fontSize === size && styles.optionSelected,
        ]}
      >
        <Text>{size}</Text>
      </Pressable>
    ))}
  </View>
</View>

Applying Settings Globally with Context

For dark mode to affect the entire app, the settings must be shared globally. Load settings at the app root (in App.tsx) and store them in a SettingsContext. Any screen that needs the current theme can read from context instead of loading from AsyncStorage every time. Only the root loads from storage once on startup.

// App.tsx
const [settings, setSettings] = React.useState<Settings>(DEFAULT_SETTINGS);

useEffect(() => {
  loadSettings().then(setSettings);
}, []);

return (
  <SettingsContext.Provider value={{ settings, updateSetting }}>
    <NavigationContainer theme={settings.darkMode ? DarkTheme : DefaultTheme}>
      <AppNavigator />
    </NavigationContainer>
  </SettingsContext.Provider>
);

Reset to Defaults Button

Add a 'Reset to Defaults' button at the bottom of the settings screen. When tapped, it calls AsyncStorage.removeItem to erase the saved settings and resets the local state to DEFAULT_SETTINGS. Confirm the action with an Alert before applying the reset, as it is a potentially destructive operation.

function handleReset() {
  Alert.alert('Reset Settings', 'Restore all settings to their defaults?', [
    { text: 'Cancel', style: 'cancel' },
    {
      text: 'Reset',
      style: 'destructive',
      onPress: async () => {
        await AsyncStorage.removeItem(SETTINGS_KEY);
        setSettings(DEFAULT_SETTINGS);
      },
    },
  ]);
}

Testing Persistence Across Restarts

To verify your settings actually persist, change a setting, close the app completely (not just background it), reopen it, and check that the changed value is shown. In Expo Go you can test this with a force-close. In a development build, shake the device to access the dev menu and reload to simulate a fresh start while keeping AsyncStorage data.

Complete Settings Screen Structure

Here is the full structure of a settings screen combining all the patterns from this lesson. The screen loads settings on mount, renders toggles and pickers that call updateSetting, applies styles that honor the dark mode setting, and includes a reset button at the bottom. This template can be customized for any app's specific preferences.

export default function SettingsScreen() {
  const [settings, setSettings] = React.useState<Settings>(DEFAULT_SETTINGS);
  const [loading, setLoading] = React.useState(true);

  useEffect(() => { loadSettings().then((s) => { setSettings(s); setLoading(false); }); }, []);

  if (loading) return <ActivityIndicator />;

  return (
    <ScrollView style={[styles.container, settings.darkMode && styles.dark]}>
      <SwitchRow label='Dark Mode' value={settings.darkMode}
        onChange={(v) => updateSetting('darkMode', v)} />
      <SwitchRow label='Notifications' value={settings.notificationsEnabled}
        onChange={(v) => updateSetting('notificationsEnabled', v)} />
      <FontSizeRow value={settings.fontSize}
        onChange={(v) => updateSetting('fontSize', v)} />
      <Button title='Reset to Defaults' onPress={handleReset} color='red' />
    </ScrollView>
  );
}

Quick Check

Test your understanding of React Native Mobile Development concepts from this lesson.

Lesson Recap

In this lesson you learned: loading on mount with useEffect restores settings from AsyncStorage before the screen renders, a single updateSetting helper merges changes and writes to AsyncStorage for any settings key, and sharing settings via Context makes preferences like dark mode available throughout the entire app. Next up we explore clearing storage and migration strategies.

자주 묻는 질문

“영구 설정 화면 만들기” 강의는 무료인가요?

네 — “영구 설정 화면 만들기” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 24/7 AI 튜터), CoddyKit PRO로 업그레이드하면 React Native Academy 강의 전체를 잠금 해제할 수 있습니다. React Native Academy 강의에는 총 4개의 강의가 포함되어 있습니다.

“영구 설정 화면 만들기”에서 뭘 배우나요?

알림과 다크 모드를 전환할 수 있는 설정 화면을 만들고 각 설정을 AsyncStorage에 저장하며 앱 시작 시 환경설정을 복원합니다. 브라우저에서 직접 실행하는 실습 코드로 React Native Academy을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.

React Native Academy을(를) 시작하는 데 경험이 필요한가요?

사전 경험은 필요하지 않습니다. CoddyKit의 React Native Academy은(는) 초급자부터 고급 학습자까지를 위해 구성되어 있으므로, 여기서 시작하거나 처음부터 시작할 수 있으며 자신의 속도대로 진행할 수 있습니다. 이것은 4개 중 3번째 강의입니다.

“영구 설정 화면 만들기” 강의는 얼마나 걸리나요?

대부분의 CoddyKit 강의는 약 5~10분이 소요됩니다. 각 강의는 간결하고 인터랙티브하여 꾸준한 진행이 가능하며, 웹과 앱에서 중단한 부분부터 바로 시작할 수 있습니다.

이 React Native Academy 강의에서 코드를 작성하고 실행할 수 있나요?

네. 모든 React Native Academy 강의에는 내장 코드 에디터가 포함되어 있으므로, 브라우저에서 바로 실제 코드를 작성하고 실행한 후 즉시 AI 피드백을 받을 수 있습니다 — 로컬 설정이 필요 없습니다.

이 강의의 모든 강의

  1. AsyncStorage로 읽고 쓰기
  2. JSON 객체 저장 및 파싱
  3. 영구 설정 화면 만들기
  4. 저장소 삭제와 마이그레이션 전략
← React Native Academy(으)로 돌아가기