Components, props and hooks
Why it matters
- React Native function components with hooks are the closest thing to Jetpack Compose outside Android: declarative UI, state that triggers re-rendering, and effects tied to the component's lifetime. Your Compose instincts transfer, but the rules differ in ways that cause real bugs.
- Most React Native bugs that Kotlin developers write are hook bugs: an effect with a wrong dependency array, a missing cleanup that leaks a listener, or a stale closure that reads an old value.
- Interviewers use stale closure, dependency array and
useCallbackquestions to separate people who memorised the API from people who understand how rendering works. - Knowing when a component re-renders (and when
React.memoskips it) is the base of React Native performance work, because rendering runs on the JS thread.
The simple explanation
- A component is like a
@Composablefunction: it takes inputs and returns a description of UI. - Props are like composable parameters: passed down by the parent, read-only for the child.
useStateis likeremember { mutableStateOf(...) }: a value that survives re-renders, and setting it schedules a new render.useEffectis likeDisposableEffect(key): it runs after the UI is committed, re-runs when its keys change, and its returned cleanup function plays the role ofonDispose.
What are components, props and hooks in React Native? A component is a JavaScript/TypeScript function that returns JSX, a description of the UI (View, Text, Pressable, or your own components). Props are the arguments a parent passes to it; the child must treat them as read-only, and when it needs to change something it calls a function the parent passed down. Hooks are functions whose names start with use that give a function component state (useState), side effects (useEffect), memoization (useMemo, useCallback) and mutable references (useRef). They replaced class lifecycle methods such as componentDidMount.
Rules of hooks. Call hooks only at the top level of a component or a custom hook, never inside conditions, loops or nested functions. React stores hook state by call order, so the order must be the same on every render. The ESLint plugin eslint-plugin-react-hooks checks this and the dependency arrays.
When does a component re-render? When its own state changes, when a context it reads changes, or when its parent re-renders. The last one surprises Compose developers: by default a child re-renders with its parent even if its props did not change. Wrapping the child in React.memo makes React skip it when every prop is the same by Object.is (reference equality for objects and functions). That is why a new object or arrow function created on each render defeats memo, and why useMemo and useCallback exist. Compose, by contrast, compares parameters with equals and skips automatically when they are stable.
Effects. useEffect(setup, deps) runs setup after React commits the render. With no array it runs after every render; with [] it runs after the first render; with [a, b] it runs when a or b changes by Object.is. If setup returns a function, React calls it before the next run and on unmount. In development, if the app is wrapped in StrictMode, React runs setup, cleanup, setup once on mount to expose missing cleanup.
| React hook | Jetpack Compose | Difference to remember |
|---|---|---|
useState(x) | remember { mutableStateOf(x) } | The value is a snapshot for this render; it does not change until the next render |
useEffect(fn, deps) | LaunchedEffect(key) / DisposableEffect(key) | Not a coroutine; cleanup is the returned function |
useMemo(fn, deps) | remember(key) { compute() } | A performance hint, not a guarantee |
useCallback(fn, deps) | remember(key) { lambda } | Only useful if a memoized child or a dependency array uses the function |
useRef(x) | remember { Holder(x) } (not State) | Changing .current does not re-render |
React.memo(Component) | Skipping when parameters are stable and equal | React compares with Object.is, Compose with equals |
Notes
- Props are read-only. To change data, the child calls a callback prop such as
onChange, and the parent updates its own state. This is the same unidirectional data flow as state hoisting in Compose. useStateuses its argument only on the first render. Pass a function (useState(() => expensiveInit())) when the initial value is costly to compute.- A state variable is a snapshot: after
setCount(count + 1),countstill has the old value until the next render. Use the updater formsetCount(c => c + 1)when the new value depends on the old one. - Updater functions must be pure. React may call them twice in development under
StrictMode, so never call an API or a callback prop inside one. useEffectwith no array runs after every render, with[]after the first render, and with[a, b]wheneveraorbchanges byObject.is.- Return a cleanup function from any effect that subscribes, starts a timer or opens a connection. React calls it before the effect re-runs and on unmount, like
onDisposeinDisposableEffect. - Every value from the component body that an effect reads belongs in its dependency array. Leaving one out gives you a stale closure; the
react-hooks/exhaustive-depslint rule catches it. - Many effects should not exist: values derived from props or state can be calculated during render, and responses to a button press belong in the event handler.
useRefholds a mutable value that survives re-renders without causing them, such as a timer ID, the previous value of something, or a reference to a native view. Do not read or write.currentduring rendering.useCallbackkeeps the same function instance between renders, anduseMemokeeps a computed value. Both only help when something compares by reference: aReact.memochild, or another hook's dependency array.- The React Compiler can add this memoization automatically at build time. Check whether your project uses it before adding
useMemoanduseCallbackby hand.
Code example
A counter that uses props, local state, a ref, an effect with cleanup, and a memoized child that skips re-rendering when its callback stays the same.
import { memo, useCallback, useEffect, useRef, useState } from 'react';
import { AppState, Button, Text, View } from 'react-native';
type CounterProps = {
initialValue: number;
step?: number;
};
// memo: re-render only when onPress is a different function (Object.is)
const IncrementButton = memo(function IncrementButton({ onPress }: { onPress: () => void }) {
return <Button title="Increment" onPress={onPress} />;
});
export function Counter({ initialValue, step = 1 }: CounterProps) {
// Like remember { mutableStateOf(initialValue) }: initialValue is read on the first render only
const [count, setCount] = useState(initialValue);
const [isActive, setIsActive] = useState(AppState.currentState === 'active');
// Survives re-renders; changing it does not trigger one
const lastAppState = useRef(AppState.currentState);
// Like DisposableEffect(Unit): subscribe after the first render, unsubscribe on unmount
useEffect(() => {
const subscription = AppState.addEventListener('change', (next) => {
if (lastAppState.current !== 'active' && next === 'active') {
console.log('App came back to the foreground');
}
lastAppState.current = next;
setIsActive(next === 'active');
});
return () => subscription.remove();
}, []);
// Stable while step is unchanged, so IncrementButton can skip re-rendering
const increment = useCallback(() => {
setCount((c) => c + step); // updater form: no stale count, no side effects inside
}, [step]);
return (
<View>
<Text>Count: {count}</Text>
<Text>{isActive ? 'In foreground' : 'In background'}</Text>
<IncrementButton onPress={increment} />
</View>
);
}useState(initialValue)readsinitialValueonly once. If the parent later passes a differentinitialValue, the counter keeps its own state, the same asrememberwithout a key.- The effect has an empty dependency array because it reads only the stable
setIsActivesetter and a ref. Its cleanup removes the listener; without it, every mount would leak a subscription. incrementis wrapped inuseCallbackwith[step], andsetCount(c => c + step)does not needcount, so the function stays the same across renders and thememochild skips re-rendering when onlycountchanges.
Run the idea in plain Kotlin
This models how React stores hook state by call order and decides whether an effect re-runs by comparing its dependencies with Object.is-style equality.
object Unset
// Object.is: primitives by value, objects by reference
fun same(a: Any?, b: Any?): Boolean =
if (a is Number || a is String || a is Boolean) a == b else a === b
class Component {
private val slots = mutableListOf<Any?>()
private var index = 0
private val pendingEffects = mutableListOf<() -> Unit>()
fun render(body: Component.() -> Unit) {
index = 0
body()
pendingEffects.forEach { it() } // effects run after the render is committed
pendingEffects.clear()
}
fun <T> useState(initial: T): Pair<T, (T) -> Unit> {
val i = index++
if (i == slots.size) slots.add(initial) // initial value is used on the first render only
@Suppress("UNCHECKED_CAST")
val value = slots[i] as T
return value to { newValue: T -> slots[i] = newValue }
}
fun useEffect(deps: List<Any?>?, effect: () -> Unit) {
val i = index++
if (i == slots.size) slots.add(Unset)
val previous = slots[i]
val changed = deps == null || previous === Unset ||
(previous as List<*>).indices.any { !same(previous[it], deps[it]) }
if (changed) {
slots[i] = deps
pendingEffects.add(effect)
}
}
}
class SearchOptions(val query: String) // plain class: no equals(), like a JS object
fun main() {
val counter = Component()
var setCount: (Int) -> Unit = {}
for (pass in 1..3) {
println("render " + pass)
counter.render {
val (count, set) = useState(0)
setCount = set
val options = SearchOptions("kotlin") // a new object on every render
useEffect(listOf(count)) { println(" [count] effect ran, count = " + count) }
useEffect(emptyList()) { println(" [] effect ran (first render only)") }
useEffect(listOf(options)) { println(" [options] effect ran (new object each render)") }
}
if (pass == 1) setCount(1)
}
}Expected output:
render 1
[count] effect ran, count = 0
[] effect ran (first render only)
[options] effect ran (new object each render)
render 2
[count] effect ran, count = 1
[options] effect ran (new object each render)
render 3
[options] effect ran (new object each render)
In production
- A screen became unresponsive in development and React logged "Maximum update depth exceeded".
- An effect with no dependency array copied a filtered list into state:
useEffect(() => { setVisible(items.filter(isVisible)); }). - Every render ran the effect, which set a new array, which caused another render. The JS thread stayed busy, so taps and JS-driven animations stopped responding.
- The team deleted the effect and state and computed the value during render:
const visible = useMemo(() => items.filter(isVisible), [items]). - Where an effect really had to set state, they listed only the inputs it reads (
[items]), never the state it writes, and turned onreact-hooks/exhaustive-depsas an error in CI.
- Users reported that an auto-save sent an older version of the form than what was on screen.
- The save ran in a
setTimeoutstarted inside an effect with an empty dependency array, so its closure kept the form values from the first render. - The lint warning about the missing dependency had been suppressed with a comment.
- The team listed the form values in the dependency array and cleared the previous timeout in the effect's cleanup, which also turned the save into a proper debounce.
- For a callback that must always see the latest values without restarting the effect, they kept the latest values in a ref updated after each render.
- They removed the lint suppression and added a review rule against new ones.
Common mistakes
- Mutating props or state. Props are read-only, and
state.items.push(x)keeps the same array reference, so React sees no change and skips the render. Create a new value:setItems([...items, x]). - Omitting dependencies in useEffect. The effect keeps using values from the render that created it: a stale closure. List every value from the component body that the effect reads.
- Forgetting effect cleanup. A listener, timer or subscription without a returned cleanup leaks on every mount, and runs twice in development under
StrictMode. - Defining a component inside another component. The inner function is a new component type on every render, so React unmounts and remounts it and its state is lost. Define components at the top level.
- Copying props into state.
useState(props.value)reads the prop only once, so the state stops following it. Calculate derived values during render instead. - Expecting useCallback alone to stop re-renders. A stable callback only helps if the child is wrapped in
React.memo(or the function is a dependency). Withoutmemo, the child re-renders with its parent anyway. AnduseCallbackwith no dependency array returns a new function every render, so it memoizes nothing.
Interview questions
Answer out loud first. Then reveal the answer and compare it at each depth.
“What is the difference between props and state?”
“How does the useEffect dependency array work?”
“What is a stale closure in the context of React hooks?”
“When should you use useMemo or useCallback?”
Quiz
Which hook stores a value that persists across renders but does NOT trigger a re-render when changed?
A component creates const options = { id: 1 } in its body and uses useEffect(fn, [options]). How often does the effect run?
A click handler calls setCount(count + 1) three times in a row. Which change makes the count go up by three?
A child component receives a callback wrapped in useCallback, but it still re-renders every time the parent does. What is the most likely reason?
0 of 4 answered
Mini task
Task: Build a memoized search screen
- Create a
SearchInputcomponent that takesvalue: stringandonChangeText: (text: string) => voidprops and renders aTextInput. Addconsole.log('SearchInput render')in its body. - Create a parent
SearchScreenthat holdsquerywithuseStateand also renders aTextshowing a clock that updates every second from a second piece of state set bysetInterval. - Start the interval in a
useEffectwith an empty dependency array and clear it in the cleanup function. Confirm that only one interval runs, even in development. - Add a
useEffectwith[query]that logs'Searching for: ' + query. - Wrap
SearchInputinReact.memoand pass itsetQuery(setters fromuseStateare already stable). Then try passing an inline arrow function instead and see what changes. Fix it withuseCallback.
Done when: typing logs the new query once per change, the clock ticking does not log SearchInput render while SearchInput is memoized and receives a stable callback, and switching to an inline arrow function makes it log on every tick.