Components, props and hooks

Learn React Native components, props and hooks (useState, useEffect, useMemo, useCallback, useRef) mapped to Jetpack Compose for Android developers. About 25 minutes.

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 useCallback questions to separate people who memorised the API from people who understand how rendering works.
  • Knowing when a component re-renders (and when React.memo skips it) is the base of React Native performance work, because rendering runs on the JS thread.

The simple explanation

  • A component is like a @Composable function: it takes inputs and returns a description of UI.
  • Props are like composable parameters: passed down by the parent, read-only for the child.
  • useState is like remember { mutableStateOf(...) }: a value that survives re-renders, and setting it schedules a new render.
  • useEffect is like DisposableEffect(key): it runs after the UI is committed, re-runs when its keys change, and its returned cleanup function plays the role of onDispose.

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 hookJetpack ComposeDifference 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 equalReact 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.
  • useState uses 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), count still has the old value until the next render. Use the updater form setCount(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.
  • useEffect with no array runs after every render, with [] after the first render, and with [a, b] whenever a or b changes by Object.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 onDispose in DisposableEffect.
  • 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-deps lint 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.
  • useRef holds 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 .current during rendering.
  • useCallback keeps the same function instance between renders, and useMemo keeps a computed value. Both only help when something compares by reference: a React.memo child, 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 useMemo and useCallback by 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) reads initialValue only once. If the parent later passes a different initialValue, the counter keeps its own state, the same as remember without a key.
  • The effect has an empty dependency array because it reads only the stable setIsActive setter and a ref. Its cleanup removes the listener; without it, every mount would leak a subscription.
  • increment is wrapped in useCallback with [step], and setCount(c => c + step) does not need count, so the function stays the same across renders and the memo child skips re-rendering when only count changes.

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

Render loop from setState in an effect
  • 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 fix
  • 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 on react-hooks/exhaustive-deps as an error in CI.
Stale form data sent by a delayed submit
  • Users reported that an auto-save sent an older version of the form than what was on screen.
  • The save ran in a setTimeout started 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 fix
  • 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). Without memo, the child re-renders with its parent anyway. And useCallback with 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

  1. Create a SearchInput component that takes value: string and onChangeText: (text: string) => void props and renders a TextInput. Add console.log('SearchInput render') in its body.
  2. Create a parent SearchScreen that holds query with useState and also renders a Text showing a clock that updates every second from a second piece of state set by setInterval.
  3. Start the interval in a useEffect with an empty dependency array and clear it in the cleanup function. Confirm that only one interval runs, even in development.
  4. Add a useEffect with [query] that logs 'Searching for: ' + query.
  5. Wrap SearchInput in React.memo and pass it setQuery (setters from useState are already stable). Then try passing an inline arrow function instead and see what changes. Fix it with useCallback.

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.

Next: Navigation and state management