A React Native component is a function that takes props and returns JSX. The only difference from the web is the elements: there is no div or span, there is View and Text. Everything else - composition, props down, events up - is the React you already know.
useState holds a value across renders and triggers a re-render when it changes. useEffect runs after render, for the things that are not rendering: starting a subscription, fetching on mount, cleaning up on unmount. Its dependency array is the part people get wrong, and the ESLint rule that checks it is worth obeying rather than silencing.
useMemo and useCallback exist to stop work happening again when nothing relevant changed. On the web they are often premature. On a mid-range Android phone they are not: a list row that re-renders because its parent passed a freshly-created function every time is a real dropped frame, and wrapping the callback is the fix. The rule is still to measure first - Module 8 shows how - but the threshold at which memoisation starts paying is much lower on a phone.
import { useState, useEffect, useMemo, useCallback } from 'react';
import { View, Text, Pressable } from 'react-native';
type Props = { articles: Article[]; query: string };
export function ArticleList({ articles, query }: Props) {
const [selected, setSelected] = useState<number | null>(null);
// Recomputed only when articles or query change - not on every render.
const visible = useMemo(
() => articles.filter((a) => a.title.toLowerCase().includes(query.toLowerCase())),
[articles, query],
);
// A stable identity, so a memoised row does not re-render for a new function.
const onPick = useCallback((id: number) => setSelected(id), []);
useEffect(() => {
// Runs after render. The returned function runs on unmount or before
// the next run - this is where a subscription is torn down.
const timer = setInterval(() => console.log('still here'), 10_000);
return () => clearInterval(timer);
}, []); // [] means once, on mount
return (
<View>
{visible.map((article) => (
<Pressable key={article.id} onPress={() => onPick(article.id)}>
<Text style={{ fontWeight: selected === article.id ? '700' : '400' }}>
{article.title}
</Text>
</Pressable>
))}
</View>
);
}
Open this example in the editor and change it. Nothing you type is saved.