Skip to main content

Understanding React Hooks and Managing State

Your goal: Give the Reading List one shared source of read/unread information, then explain when a component needs an Effect.

Before you begin: Complete Lists and Conditional Rendering. Open the same Expo project and run npx expo start. We will keep its three books, FlatList, and card styling.

By the end, you will be able to:

  • Follow the rules for calling Hooks.
  • Move state to a parent and pass a callback to a child.
  • Update one book without changing existing state objects.
  • Calculate a completed-book count and progress indicator during rendering.
  • Explain Effect dependencies, cleanup, and development Strict Mode.

What is a Hook?​

A Hook is a React function that lets a function component use capabilities such as state or external synchronization. Hooks also let you organize reusable component logic in custom Hooks. You have already used one: useState connects a component to React’s state mechanism so a value can survive renders and a setter can request an update.

Hook names begin with use followed by a capital letter, as in useState or a custom useReadingTimer. Naming a regular helper this way does not make it stateful; reserve that naming pattern for Hooks. The publication name useReactNative echoes this familiar convention; it is not a built-in Hook or a package you need to import.

HookWhat it is for
useStateRemember information used to render the interface.
useEffectSynchronize with an external system, such as a timer or subscription.
useRefKeep a mutable reference across renders; changing it does not trigger rendering.
useMemoCache a calculation between renders when its dependencies have not changed; a performance tool, not a requirement for correct state.

We will focus on useState and useEffect. You do not need the other two for this Reading List. See the built-in Hooks overview.

Follow the Hook rules​

Call these Hooks at the top level of a function component or custom Hook, before conditional returns. Do not call them inside loops, conditions, event handlers, or ordinary helper functions.

React relies on a consistent order of Hook calls across renders to associate state with the right call. Calling a setter from a press handler is fine; calling useState there is not. See the Rules of Hooks.

Review useState as a snapshot​

Previously, each BookCard contained:

The earlier card’s state
const [isRead, setIsRead] = useState(false);

false is the initial state, used when the card first mounts. isRead is the current state for this render. setIsRead is the setter, which requests another render with a new value. Calling the component again does not reinitialize its state.

Each render receives a snapshot of state. The setter does not rewrite a value in a handler that is already running:

Inside the earlier BookCard
function markRead() {
setIsRead(true);
console.log(isRead); // Still this render’s value, not the requested update.
}

For a toggle, calculate the next value from the pending previous value:

setIsRead(previous => !previous);

This functional update is useful when the next value depends on the previous one, including when updates are queued together. Keep updater functions pure: return the next state without modifying their inputs or performing side effects. We will use the same pattern for an array. See useState and state as a snapshot.

Lift read status into the screen​

Local card state worked while only the card needed it. Now the screen needs to count completed books and show progress. The summary and cards must agree. Also, FlatList can unmount cards outside its render window; state stored only in those cards can disappear.

The state owner is the component that holds a value and updates it. Lifting state up means moving that information to the nearest parent that needs to coordinate it. Here that parent is HomeScreen. Each book will carry its read status:

The book data shape
type Book = {
id: string;
title: string;
author: string;
isRead: boolean;
};

Add isRead: false to each of the original three book objects and name that starting array initialBooks. Inside HomeScreen, initialize the collection:

At the top of HomeScreen
const [books, setBooks] = useState<Book[]>(initialBooks);

Book[] tells TypeScript this state is an array of books. The full example includes the entire starting array. Treat initialBooks and the current books objects as read-only.

Pass data down and actions back​

BookCard no longer calls useState. It receives the value to display and a function to call when pressed:

The card’s new inputs
type BookCardProps = {
title: string;
author: string;
isRead: boolean;
onToggleRead: () => void;
};

() => void describes a function with no arguments and no return value the card needs. The card calls it through onPress={onToggleRead}. It does not edit isRead or keep a second copy of it in local state.

One toggle, from press to updated UI
HomeScreen owns books
| passes isRead and callback
v
BookCard shows status
| press calls onToggleRead()
v
HomeScreen updates the chosen book
| React renders updated props
v
Card status + summary agree

The parent supplies onToggleRead={() => toggleRead(item.id)}. That function remembers which book the card represents. Calling the callback notifies the parent of the action; props still flow downward. See sharing state between components.

Parent state survives a card being unmounted and recreated while the screen remains mounted: the returning card reads its status from books. Unmounting the screen or reloading the app can still reset everything. This is shared in-memory state, not persistent storage.

Update the array without mutation​

Define this handler inside HomeScreen, after the state declaration:

Toggle one book by ID
function toggleRead(selectedId: string) {
setBooks(previous =>
previous.map(book =>
book.id === selectedId
? { ...book, isRead: !book.isRead }
: book
)
);
}

Read the update in four steps:

  1. React supplies the pending array as previous.
  2. map() creates a new array by visiting each book.
  3. For the matching ID, { ...book } copies the book’s properties into a new object. The following isRead property replaces the copied value with its opposite.
  4. Other books are returned unchanged. The setter receives the new array as the next state.

This is an immutable update: existing objects are left intact. Copying only the array is not enough if you then modify an object inside it. React needs the new state value, and other code may still refer to the previous snapshot. See updating arrays in state.

Calculate progress from books​

The number of completed books is already determined by the collection:

Inside HomeScreen, before return
const completedCount = books.filter(book => book.isRead).length;
const progressPercent = books.length === 0
? 0
: (completedCount / books.length) * 100;

filter() produces an array of books whose isRead value is true; .length counts them. The percentage divides that count by the total. Checking for an empty collection avoids division by zero.

These are derived values: calculate them again during rendering. Do not create separate state for completedCount, and do not use an Effect to keep it synchronized. One book update now drives both the card and summary without a second value that could get out of step. If a value can be calculated from existing props or state, it usually does not need its own state. See choosing the state structure.

The complete screen shows “1 of 3 books read” alongside a simple track and filled View. The fill’s percentage width adapts to the screen, and the visible text and accessibility value communicate progress without relying on color.

Run the complete Reading List​

Replace src/app/index.tsx, or the screen file you used in the previous lesson, with this code. Keep the existing Expo Router layout and react-native-safe-area-context setup. No new installation is needed in the established project.

What changes in this lesson: Everything still fits in src/app/index.tsx. HomeScreen takes ownership of read status, BookCard receives it through props, and the header gains a progress summary. The existing list and styles stay in place.

This Reading List needs no Effect: a press handler updates state, and rendering calculates progress. The timer experiment afterward is separate; restore this complete screen before starting Navigation.

src/app/index.tsx — complete Reading List
import { useState } from 'react';
import { FlatList, Pressable, StyleSheet, Text, View } from 'react-native';
import { SafeAreaView } from 'react-native-safe-area-context';

type Book = {
id: string;
title: string;
author: string;
isRead: boolean;
};

const initialBooks: Book[] = [
{ id: 'hobbit', title: 'The Hobbit', author: 'J. R. R. Tolkien', isRead: false },
{ id: 'earthsea', title: 'A Wizard of Earthsea', author: 'Ursula K. Le Guin', isRead: false },
{ id: 'secret-garden', title: 'The Secret Garden', author: 'Frances Hodgson Burnett', isRead: false },
];

type BookCardProps = {
title: string;
author: string;
isRead: boolean;
onToggleRead: () => void;
};

function BookCard({ title, author, isRead, onToggleRead }: BookCardProps) {
const buttonLabel = isRead ? 'Mark as unread' : 'Mark as read';

return (
<View style={styles.card}>
<View style={styles.bookRow}>
<Text
style={styles.bookIcon}
accessible={false}
accessibilityElementsHidden={true}
importantForAccessibility="no"
>
📖
</Text>
<View style={styles.details}>
<Text style={styles.bookTitle}>{title}</Text>
<Text style={styles.author}>{author}</Text>
</View>
</View>
<Text style={[styles.status, isRead && styles.readStatus]}>
Status: {isRead ? 'Read' : 'Unread'}
</Text>
<Pressable
style={({ pressed }) => [styles.button, pressed && styles.buttonPressed]}
onPress={onToggleRead}
accessibilityRole="button"
accessibilityLabel={buttonLabel + ': ' + title}
>
<Text style={styles.buttonText}>{buttonLabel}</Text>
</Pressable>
</View>
);
}

export default function HomeScreen() {
const [books, setBooks] = useState<Book[]>(initialBooks);
const completedCount = books.filter(book => book.isRead).length;
const progressPercent = books.length === 0
? 0
: (completedCount / books.length) * 100;

function toggleRead(selectedId: string) {
setBooks(previous =>
previous.map(book =>
book.id === selectedId
? { ...book, isRead: !book.isRead }
: book
)
);
}

return (
<SafeAreaView style={styles.screen}>
<FlatList
data={books}
keyExtractor={book => book.id}
renderItem={({ item }) => (
<BookCard
title={item.title}
author={item.author}
isRead={item.isRead}
onToggleRead={() => toggleRead(item.id)}
/>
)}
contentContainerStyle={styles.content}
ListHeaderComponent={
<View style={styles.header}>
<Text style={styles.heading} accessibilityRole="header">
My Reading List
</Text>
<Text style={styles.subtitle}>Find your next good read</Text>
<Text style={styles.summary}>
{completedCount} of {books.length} books read
</Text>
<View
style={styles.progressTrack}
accessible={true}
accessibilityRole="progressbar"
accessibilityLabel="Reading progress"
accessibilityValue={{
min: 0,
max: 100,
now: Math.round(progressPercent),
text: `${completedCount} of ${books.length} books read`,
}}
>
<View
style={[styles.progressFill, { width: `${progressPercent}%` }]}
/>
</View>
</View>
}
ItemSeparatorComponent={() => <View style={styles.separator} />}
ListEmptyComponent={
<View style={styles.card}>
<Text style={styles.bookTitle}>Your reading list is empty</Text>
<Text style={styles.author}>
Add a book to the initialBooks array to start your list.
</Text>
</View>
}
/>
</SafeAreaView>
);
}

const styles = StyleSheet.create({
screen: { flex: 1, backgroundColor: '#f1f5f9' },
content: { padding: 16 },
separator: { height: 16 },
header: { gap: 6, marginBottom: 20 },
heading: { color: '#0f172a', fontSize: 28, fontWeight: '700' },
subtitle: { color: '#475569', fontSize: 16 },
summary: { color: '#334155', fontSize: 16, fontWeight: '600' },
progressTrack: {
height: 12,
borderRadius: 6,
backgroundColor: '#cbd5e1',
overflow: 'hidden',
},
progressFill: { height: '100%', backgroundColor: '#1e40af' },
card: {
padding: 16,
gap: 12,
backgroundColor: '#ffffff',
borderWidth: 1,
borderColor: '#cbd5e1',
borderRadius: 16,
},
bookRow: { flexDirection: 'row', alignItems: 'flex-start', gap: 12 },
bookIcon: { fontSize: 28, flexShrink: 0 },
details: { flex: 1, gap: 4 },
bookTitle: { color: '#0f172a', fontSize: 20, fontWeight: '600' },
author: { color: '#475569', fontSize: 16 },
status: {
alignSelf: 'flex-start',
maxWidth: '100%',
paddingHorizontal: 10,
paddingVertical: 6,
borderRadius: 8,
backgroundColor: '#e2e8f0',
color: '#334155',
fontSize: 14,
fontWeight: '600',
},
readStatus: { backgroundColor: '#dcfce7', color: '#166534' },
button: {
minHeight: 48,
padding: 12,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#1e40af',
borderRadius: 10,
},
buttonPressed: { backgroundColor: '#1e3a8a' },
buttonText: { color: '#ffffff', fontSize: 16, fontWeight: '600', textAlign: 'center' },
});

Follow one press​

Press Mark as read on The Hobbit. The card calls its callback, toggleRead replaces that book in the parent array, and the next render supplies the updated isRead prop. The header now reads 1 of 3 books read, and the bar fills about a third of its track. Press again to return to zero. The other two books keep their values.

FlatList receives a new data array on each update. Stable IDs still identify items; the state now lives above the virtualized cards. The responsive card styles, generous button minimum height, safe areas, and empty presentation remain from the previous lessons.

To try the empty screen, temporarily use const initialBooks: Book[] = []; and fully reload the app. The count becomes 0 of 0 books read, the fill stays at zero, and the friendly empty card appears. Restore the array and reload afterward. Fast Refresh can preserve state during edits; changing the initializer does not reset an already mounted screen’s state.

On a phone, check a narrow screen and larger accessibility text. Reach the last button by scrolling and check that status, summary, and progress agree. A screen reader should announce the button’s action and book, plus the progress value.

Use Effects for external synchronization​

Rendering calculates what the interface should show. An Effect synchronizes a component with something outside React, such as a platform subscription or an interval managed by the timer system. Registering a timer during rendering would create more timers each time React renders. An Effect starts the timer in its setup function and returns a cleanup function to stop it when that setup is no longer needed.

React runs Effect setup after a render is committed—after React applies its changes. Do not assume an Effect runs before the user can see the updated interface. Effects do not run during static server rendering.

The following are syntax sketches, not code to add to the Reading List:

No dependency array
useEffect(() => {
// Setup after every committed render.
// Return cleanup here if setup creates a resource.
});
An empty dependency array
useEffect(() => {
// Setup when this component mounts.
return () => {
// Undo setup when this component unmounts.
};
}, []);
A dependency
useEffect(() => {
// Setup on mount, then again when someValue changes.
return () => {
// Undo this setup before the next setup or on unmount.
};
}, [someValue]);

List the reactive values read by setup—such as props or state—in the dependency array. React compares each dependency with its previous value. When one changes, React runs the old cleanup before setup with the new values. On unmount, React runs the final cleanup. With no array, cleanup precedes each subsequent setup; [] is appropriate only when setup needs no changing reactive values. Do not omit dependencies merely to stop an Effect running. See useEffect.

Expect a development cleanup check​

Under development Strict Mode, React can run an extra setup → cleanup → setup cycle when an Effect mounts. This checks whether cleanup correctly undoes setup. It is not a reason to disable Strict Mode or hide repeated setup. Make the Effect safe to stop and restart. The extra development check is distinct from normal reruns when dependencies change. See Strict Mode’s Effect checks.

Try a separate elapsed-time display​

For this isolated experiment, save your Reading List code, then temporarily replace the same screen file with the following example. Restore the Reading List afterward. Keep the surrounding Router and safe-area setup in place.

Temporary screen — timer experiment
import { useEffect, useState } from 'react';
import { StyleSheet, Text } from 'react-native';
import { SafeAreaView } from 'react-native-safe-area-context';

export default function TimerScreen() {
const [seconds, setSeconds] = useState(0);

useEffect(() => {
const intervalId = setInterval(() => {
setSeconds(previous => previous + 1);
}, 1000);

return () => {
clearInterval(intervalId);
};
}, []);

return (
<SafeAreaView style={styles.screen}>
<Text style={styles.heading}>Time on this screen</Text>
<Text style={styles.elapsed}>{seconds} seconds</Text>
</SafeAreaView>
);
}

const styles = StyleSheet.create({
screen: { flex: 1, padding: 24, gap: 12, backgroundColor: '#f1f5f9' },
heading: { fontSize: 24, fontWeight: '700', color: '#0f172a' },
elapsed: { fontSize: 18, color: '#334155' },
});

The timer system is external to React. Setup registers a callback approximately every 1,000 milliseconds. Each callback uses a functional update, so it does not capture an old seconds value. Setup reads no changing props or state; the setter has a stable identity, so [] is appropriate here.

Cleanup cancels the interval created by that setup. Without it, an unmounted screen could leave a timer running, and remounting or development checks could accumulate timers. With cleanup, each setup has a matching cancellation. See React Native’s timers documentation.

Watch the number rise while the screen stays mounted. This counts timer ticks as approximate elapsed seconds; timers can be delayed or paused when the app is busy or backgrounded. It is not an accurate background stopwatch. Navigating away does not necessarily unmount a Router screen, so cleanup follows unmounting, not simply loss of focus. Navigation lifecycle handling belongs to a later lesson.

Recognize common mistakes​

These fragments contrast mistakes with the intended pattern. Names such as showProgress, toggleRead, and selectedId stand for values in the surrounding component.

Calling Hooks conditionally or in a loop​

Incorrect
if (showProgress) {
const [books, setBooks] = useState<Book[]>(initialBooks);
}
Correct: call the Hook before choosing UI
const [books, setBooks] = useState<Book[]>(initialBooks);
// Use showProgress to choose JSX later.

Do not move Hook calls into books.map(...) or a press handler either. Use a component’s top-level Hook call; its event handlers can call the setter.

Mutating state directly​

Incorrect: changes an existing object
books[0].isRead = true;
setBooks(books);
Correct: replace the chosen object and array
setBooks(previous => previous.map(book =>
book.id === selectedId ? { ...book, isRead: true } : book
));

Keeping a second copy of derived information​

Unnecessary state and synchronization
const [completedCount, setCompletedCount] = useState(0);
useEffect(() => {
setCompletedCount(books.filter(book => book.isRead).length);
}, [books]);
Calculate it during rendering instead
const completedCount = books.filter(book => book.isRead).length;

Using an Effect for a button action​

Unnecessary detour through state and an Effect
const [requestedId, setRequestedId] = useState<string | null>(null);
useEffect(() => {
if (requestedId !== null) toggleRead(requestedId);
}, [requestedId, toggleRead]);
// A button sets requestedId instead of performing the action.
Handle the action directly
<Pressable onPress={() => toggleRead(item.id)}>
<Text>Toggle read status</Text>
</Pressable>

The Effect detour can also repeat unexpectedly as function dependencies change. The existing accessible card uses the direct callback approach. See You Might Not Need an Effect.

Forgetting cleanup​

Incorrect: leaves the interval running
useEffect(() => {
setInterval(() => setSeconds(previous => previous + 1), 1000);
}, []);
Correct: cancel the interval this setup created
useEffect(() => {
const id = setInterval(() => setSeconds(previous => previous + 1), 1000);
return () => clearInterval(id);
}, []);

Updating a dependency in an Effect loop​

Incorrect: every update triggers another setup
useEffect(() => {
setSeconds(seconds + 1);
}, [seconds]);

Each setup changes seconds, which triggers another setup. For the timer experiment, use the interval with cleanup shown above: ticks request updates, and the Effect does not depend on seconds. For a button-driven counter, increment in its event handler. Do not fix dependency loops by hiding values the Effect reads.

Practice​

  1. Reset progress. Add an accessible Reset Reading Progress button in the screen header. Update the parent array so every book becomes unread without modifying existing objects. Check that the cards and summary reset together.
  2. Celebrate completion. Display a message when every book is read. Handle an empty array deliberately so an empty list does not accidentally trigger the message. Derive the condition from books.
  3. Restyle progress. Change the fill’s color based on completion percentage. Keep the written count and accessibility value so the information does not depend on color alone.

Check your understanding​

  1. Why does moving read status to HomeScreen help both the summary and virtualized cards?
  2. Which parts of the book collection are copied when one book is toggled?
  3. Why does completedCount need neither a setter nor an Effect?
  4. What happens to the old Effect setup when a dependency changes?
  5. Why does the timer return a function, and why can development Strict Mode call it before final unmount?
Compare your answers

The parent owns one collection shared by the summary and cards, and it outlives individual card unmounts. An update creates a new array and a new object for the selected book; other objects stay unchanged. The completed count can be calculated from that array during rendering. A changed dependency causes cleanup of the old setup before a new setup. The timer’s returned function cancels its interval; Strict Mode’s extra development cycle checks that setup can be cleaned up and restarted safely.

You are ready to continue when: You can trace a press from card to parent and back, derive progress from one collection, and explain why the timer needs an Effect while the Reading List does not.

Return to the learning path for further resources.

Official references​