대화형 카운터 앱 만들기
props와 상태를 조합해 증가, 감소, 초기화 버튼으로 UI를 반응적으로 업데이트하는 카운터 컴포넌트를 만듭니다.
대화형 카운터 앱 만들기은(는) CoddyKit의 무료 React Native Academy 강의입니다. 이것은 4개 중 4번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 AI 튜터와 함께 브라우저에서 직접 실습할 수 있습니다. 이 강의는 React Native Academy 학습 경로의 일부이며, 진행 상황이 웹과 CoddyKit 앱에 동기화됩니다. React Native Academy 강의에는 총 4개의 강의가 포함되어 있습니다.
이 강의의 일부는 아직 번역되지 않았으며 영어로 표시됩니다.
Counter App Project Plan
This lesson builds a complete interactive counter app that applies all concepts learned in this course: props for passing data, useState for managing the count, lifted state for sharing between sibling components, and StyleSheet for visual polish. The app will have a display component that shows the current count, three control buttons (Increment, Decrement, Reset), a history log of recent changes, and a step-size selector to change how much each button increments. Planning the component structure before coding prevents confusion.
// Component tree for the Counter App:
// App
// ├── CountDisplay ← shows current count (receives count prop)
// ├── CountControls ← increment/decrement/reset buttons
// │ └── ControlButton ← reusable button component
// ├── StepSelector ← choose step size (1, 5, 10)
// └── HistoryLog ← list of recent operationsSetting Up App State
The App (or screen) component owns all the state: the current count, the step size, and the history log. Because CountDisplay, CountControls, and HistoryLog are siblings that all need different aspects of this state, lifting it to the parent is correct. The history is an array of strings (operation descriptions) that grows with each action. Using a single parent to own all state keeps the logic centralized and easy to follow.
import { useState } from 'react';
export default function CounterApp() {
const [count, setCount] = useState(0);
const [step, setStep] = useState(1);
const [history, setHistory] = useState([]);
function addHistory(message) {
setHistory(prev => [message, ...prev].slice(0, 10)); // keep last 10
}
function increment() {
setCount(prev => prev + step);
addHistory(`+${step} → ${count + step}`);
}
function decrement() {
setCount(prev => prev - step);
addHistory(`-${step} → ${count - step}`);
}
function reset() {
setCount(0);
addHistory('Reset → 0');
}
return null; // UI rendered below
}CountDisplay Component
The CountDisplay component is a pure presentational component: it receives the count as a prop and displays it with a dynamic color. Positive counts are green, negative are red, and zero is gray. This is a great example of derived presentation logic — the component doesn't manage state, it just transforms its input prop into visual output. The large number display uses a dramatic font size to make the counter the visual center of attention.
import { View, Text, StyleSheet } from 'react-native';
export default function CountDisplay({ count }) {
const color = count > 0 ? '#2ecc71' : count < 0 ? '#e74c3c' : '#95a5a6';
return (
<View style={styles.container}>
<Text style={styles.label}>Current Count</Text>
<Text style={[styles.count, { color }]}>{count}</Text>
<View style={[styles.bar, { backgroundColor: color }]} />
</View>
);
}
const styles = StyleSheet.create({
container: { alignItems: 'center', paddingVertical: 32 },
label: { fontSize: 14, color: '#999', letterSpacing: 1, textTransform: 'uppercase' },
count: { fontSize: 96, fontWeight: '800', marginVertical: 8 },
bar: { width: 60, height: 4, borderRadius: 2 },
});Reusable ControlButton Component
Build a reusable ControlButton component that accepts a label, an icon, an onPress callback, and a variant ('primary', 'danger', or 'ghost'). The variant determines the button's color scheme. Using a single button component for increment, decrement, and reset avoids duplicating button style code. Each variant maps to a different color set, and the button applies the correct styles automatically based on the prop value.
import { TouchableOpacity, Text, StyleSheet } from 'react-native';
const VARIANT_COLORS = {
primary: { bg: '#4f86f7', text: '#fff', border: '#4f86f7' },
danger: { bg: '#e74c3c', text: '#fff', border: '#e74c3c' },
ghost: { bg: 'transparent', text: '#666', border: '#ddd' },
};
export default function ControlButton({ label, onPress, variant = 'ghost' }) {
const colors = VARIANT_COLORS[variant];
return (
<TouchableOpacity
style={[styles.btn, { backgroundColor: colors.bg, borderColor: colors.border }]}
onPress={onPress}
activeOpacity={0.75}
>
<Text style={[styles.label, { color: colors.text }]}>{label}</Text>
</TouchableOpacity>
);
}
const styles = StyleSheet.create({
btn: { flex: 1, paddingVertical: 14, borderRadius: 12, borderWidth: 1.5, alignItems: 'center', justifyContent: 'center' },
label: { fontSize: 16, fontWeight: '700' },
});CountControls Layout
The CountControls component renders the three control buttons in a horizontal row. It receives onIncrement, onDecrement, and onReset callback props from the parent. The decrement button uses the 'ghost' variant, increment uses 'primary', and reset uses 'danger'. A flexDirection: 'row' with gap: 10 lays out the three buttons side by side, each taking equal width via flex: 1.
import { View, StyleSheet } from 'react-native';
import ControlButton from './ControlButton';
export default function CountControls({ onIncrement, onDecrement, onReset, step }) {
return (
<View style={styles.row}>
<ControlButton label={`-${step}`} onPress={onDecrement} variant='ghost' />
<ControlButton label='Reset' onPress={onReset} variant='danger' />
<ControlButton label={`+${step}`} onPress={onIncrement} variant='primary' />
</View>
);
}
const styles = StyleSheet.create({
row: {
flexDirection: 'row',
gap: 10,
paddingHorizontal: 20,
marginBottom: 24,
},
});StepSelector Component
The StepSelector lets users choose how much each button adds or subtracts. It renders a row of step option buttons (1, 5, 10, 25). The currently selected step is visually highlighted. When the user taps a step, it calls the onStepChange callback prop, which updates the step state in the parent App. The parent then passes the new step to CountControls so the button labels update accordingly. This is lifted state in action: the selection lives in the parent, shared between the selector and the controls.
import { View, Text, TouchableOpacity, StyleSheet } from 'react-native';
const STEPS = [1, 5, 10, 25];
export default function StepSelector({ step, onStepChange }) {
return (
<View style={styles.container}>
<Text style={styles.label}>Step Size</Text>
<View style={styles.row}>
{STEPS.map(s => (
<TouchableOpacity
key={s}
style={[styles.option, s === step && styles.selected]}
onPress={() => onStepChange(s)}
>
<Text style={[styles.optionText, s === step && styles.selectedText]}>
{s}
</Text>
</TouchableOpacity>
))}
</View>
</View>
);
}
const styles = StyleSheet.create({
container: { alignItems: 'center', marginBottom: 24 },
label: { fontSize: 13, color: '#999', marginBottom: 10, textTransform: 'uppercase', letterSpacing: 1 },
row: { flexDirection: 'row', gap: 10 },
option: { width: 52, height: 44, borderRadius: 10, borderWidth: 1.5, borderColor: '#ddd', alignItems: 'center', justifyContent: 'center' },
selected: { borderColor: '#4f86f7', backgroundColor: '#4f86f7' },
optionText: { fontSize: 16, fontWeight: '600', color: '#666' },
selectedText: { color: '#fff' },
});HistoryLog Component
The HistoryLog component displays the last 10 operations in a scrollable list. It receives the history array as a prop. Each entry shows an operation description (e.g., '+5 → 15') with a color-coded indicator — green for increments, red for decrements, and orange for resets. Using FlatList handles smooth scrolling if the history fills up. A header shows 'Recent Operations' and a count badge indicates how many operations are recorded.
import { View, Text, FlatList, StyleSheet } from 'react-native';
function EntryColor(text) {
if (text.startsWith('+')) return '#2ecc71';
if (text.startsWith('-')) return '#e74c3c';
return '#f39c12';
}
export default function HistoryLog({ history }) {
if (history.length === 0) return null;
return (
<View style={styles.container}>
<Text style={styles.header}>Recent Operations ({history.length})</Text>
<FlatList
data={history}
keyExtractor={(_, i) => i.toString()}
renderItem={({ item }) => (
<View style={styles.entry}>
<View style={[styles.dot, { backgroundColor: EntryColor(item) }]} />
<Text style={styles.text}>{item}</Text>
</View>
)}
scrollEnabled={false}
/>
</View>
);
}
const styles = StyleSheet.create({
container: { marginHorizontal: 20, padding: 16, backgroundColor: '#f8f9fa', borderRadius: 16 },
header: { fontSize: 13, color: '#999', fontWeight: '600', marginBottom: 10, textTransform: 'uppercase', letterSpacing: 0.5 },
entry: { flexDirection: 'row', alignItems: 'center', paddingVertical: 6, gap: 10 },
dot: { width: 8, height: 8, borderRadius: 4 },
text: { fontSize: 14, color: '#444' },
});Assembling the Full Counter App
Combine all components in the App with the lifted state. The parent holds count, step, and history. It defines the increment, decrement, and reset handler functions that update all three pieces of state atomically. These handlers are passed as callback props to CountControls. The step is passed to both StepSelector (for display) and CountControls (for button labels). The history array is passed to HistoryLog. The entire app's behavior is coordinated from this single parent component.
import { useState } from 'react';
import { SafeAreaView, ScrollView, StyleSheet } from 'react-native';
import CountDisplay from './CountDisplay';
import CountControls from './CountControls';
import StepSelector from './StepSelector';
import HistoryLog from './HistoryLog';
export default function CounterApp() {
const [count, setCount] = useState(0);
const [step, setStep] = useState(1);
const [history, setHistory] = useState([]);
function addHistory(msg) {
setHistory(prev => [msg, ...prev].slice(0, 10));
}
function increment() { setCount(p => { const n = p + step; addHistory('+'+step+' → '+n); return n; }); }
function decrement() { setCount(p => { const n = p - step; addHistory('-'+step+' → '+n); return n; }); }
function reset() { setCount(0); addHistory('Reset → 0'); }
return (
<SafeAreaView style={styles.safe}>
<ScrollView contentContainerStyle={styles.content}>
<CountDisplay count={count} />
<StepSelector step={step} onStepChange={setStep} />
<CountControls
step={step}
onIncrement={increment}
onDecrement={decrement}
onReset={reset}
/>
<HistoryLog history={history} />
</ScrollView>
</SafeAreaView>
);
}
const styles = StyleSheet.create({
safe: { flex: 1, backgroundColor: '#fff' },
content: { paddingBottom: 32 },
});Adding Haptic Feedback
Polish the counter app with haptic feedback using the expo-haptics module. Light haptic on increment, warning haptic on decrement, and a strong notification on reset. Haptic feedback makes the buttons feel more physical and satisfying, significantly improving the tactile experience on real devices. Call the haptic function inside each handler, right before updating state. Haptic feedback is silent when called on simulators — test on a real device to feel the difference.
import * as Haptics from 'expo-haptics';
// Install: npx expo install expo-haptics
function increment() {
Haptics.impactAsync(Haptics.ImpactFeedbackStyle.Light);
setCount(prev => {
const next = prev + step;
addHistory('+' + step + ' → ' + next);
return next;
});
}
function decrement() {
Haptics.impactAsync(Haptics.ImpactFeedbackStyle.Medium);
setCount(prev => {
const next = prev - step;
addHistory('-' + step + ' → ' + next);
return next;
});
}
function reset() {
Haptics.notificationAsync(Haptics.NotificationFeedbackType.Warning);
setCount(0);
addHistory('Reset → 0');
}Keyboard Accessibility and usability
Add final accessibility touches to the counter app. Use accessibilityLabel on each button so screen readers announce meaningful descriptions. Use accessibilityState={{ selected: s === step }} on the step selector options to communicate the selected state to assistive technology. Add a accessibilityLiveRegion='polite' to the count display so screen readers announce the new count whenever it changes. These small additions make your app usable by the millions of people who rely on accessibility features on their phones.
// Accessibility additions
// CountDisplay:
<Text
accessibilityLiveRegion='polite'
accessibilityLabel={'Current count: ' + count}
style={[styles.count, { color }]}
>
{count}
</Text>
// ControlButton:
<TouchableOpacity
accessibilityRole='button'
accessibilityLabel={'Increment by ' + step}
onPress={onPress}
style={...}
>
// StepSelector option:
<TouchableOpacity
accessibilityRole='radio'
accessibilityState={{ selected: s === step }}
accessibilityLabel={'Step size ' + s}
onPress={() => onStepChange(s)}
>Persisting the Counter to AsyncStorage
Enhance the counter app by saving the count to AsyncStorage so it survives app restarts. Use useEffect to watch the count value and write it to AsyncStorage whenever it changes. On the first render, read the saved value from AsyncStorage and initialize the count state. This is a minimal but complete example of local data persistence — the same pattern scales to saving user preferences, form drafts, and app configuration. AsyncStorage writes are asynchronous and should not block UI updates.
import AsyncStorage from '@react-native-async-storage/async-storage';
import { useState, useEffect } from 'react';
// npx expo install @react-native-async-storage/async-storage
const COUNT_KEY = '@counter_value';
export default function PersistentCounter() {
const [count, setCount] = useState(0);
const [loaded, setLoaded] = useState(false);
// Load saved count on mount
useEffect(() => {
AsyncStorage.getItem(COUNT_KEY)
.then(stored => {
if (stored !== null) setCount(parseInt(stored, 10));
})
.finally(() => setLoaded(true));
}, []);
// Save count whenever it changes (after initial load)
useEffect(() => {
if (!loaded) return;
AsyncStorage.setItem(COUNT_KEY, count.toString());
}, [count, loaded]);
if (!loaded) return null; // wait for saved value before rendering
return (
<>{/* CountDisplay, CountControls, etc. */}</>
);
}Quick Check
Test your understanding of React Native Mobile Development concepts from this lesson.
Lesson Recap
In this lesson you learned: component decomposition breaks a complex screen into focused, reusable pieces, lifted state in the parent component coordinates behavior across sibling components, and callback props + haptic feedback make the counter interactive and tactile. Next up we explore handling user input with TextInput, touch events, and form components.
자주 묻는 질문
“대화형 카운터 앱 만들기” 강의는 무료인가요?
네 — “대화형 카운터 앱 만들기” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 24/7 AI 튜터), CoddyKit PRO로 업그레이드하면 React Native Academy 강의 전체를 잠금 해제할 수 있습니다. React Native Academy 강의에는 총 4개의 강의가 포함되어 있습니다.
“대화형 카운터 앱 만들기”에서 뭘 배우나요?
props와 상태를 조합해 증가, 감소, 초기화 버튼으로 UI를 반응적으로 업데이트하는 카운터 컴포넌트를 만듭니다. 브라우저에서 직접 실행하는 실습 코드로 React Native Academy을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.
React Native Academy을(를) 시작하는 데 경험이 필요한가요?
사전 경험은 필요하지 않습니다. CoddyKit의 React Native Academy은(는) 초급자부터 고급 학습자까지를 위해 구성되어 있으므로, 여기서 시작하거나 처음부터 시작할 수 있으며 자신의 속도대로 진행할 수 있습니다. 이것은 4개 중 4번째 강의입니다.
“대화형 카운터 앱 만들기” 강의는 얼마나 걸리나요?
대부분의 CoddyKit 강의는 약 5~10분이 소요됩니다. 각 강의는 간결하고 인터랙티브하여 꾸준한 진행이 가능하며, 웹과 앱에서 중단한 부분부터 바로 시작할 수 있습니다.
이 React Native Academy 강의에서 코드를 작성하고 실행할 수 있나요?
네. 모든 React Native Academy 강의에는 내장 코드 에디터가 포함되어 있으므로, 브라우저에서 바로 실제 코드를 작성하고 실행한 후 즉시 AI 피드백을 받을 수 있습니다 — 로컬 설정이 필요 없습니다.
이 강의의 모든 강의
- Props로 데이터 전달하기
- useState로 컴포넌트 상태 관리하기
- 상태 끌어올리기
- 대화형 카운터 앱 만들기