React Native
View Size
Mobile Development
UI Components
JavaScript

Get size of a View in React Native

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

Introduction

In React Native, view size is not final during initial render, so reading dimensions too early often returns zero or stale values. The standard pattern is to use onLayout callbacks or measurement APIs after layout completes.

Choosing between declarative onLayout and imperative measure depends on your component structure and timing needs. For most app UI logic, onLayout is simpler and more reliable.

A predictable measurement strategy prevents animation glitches and incorrect dynamic layouts.

Core Sections

Define compatibility and runtime assumptions

Complex implementation issues usually appear where compatibility assumptions are implicit. Cross-compilation needs ABI and toolchain alignment. RL environments need strict spec contracts. Registry pulls need token scope and path correctness. UI measurement and WPF styling need lifecycle timing assumptions.

Before coding, capture one known input and expected output so behavior can be validated quickly after each change.

Build a minimal implementation first

Keep baseline implementation compact and deterministic. Separate configuration from logic and keep side effects explicit.

tsx
1import React, { useState } from 'react';
2import { View, Text, LayoutChangeEvent } from 'react-native';
3
4export default function SizeDemo() {
5  const [size, setSize] = useState({ width: 0, height: 0 });
6
7  const onLayout = (e: LayoutChangeEvent) => {
8    const { width, height } = e.nativeEvent.layout;
9    setSize({ width, height });
10  };
11
12  return (
13    <View onLayout={onLayout} style={{ padding: 16, backgroundColor: '#eef' }}>
14      <Text>{`w=${size.width}, h=${size.height}`}</Text>
15    </View>
16  );
17}

Once the baseline works, expand gradually while preserving testability. Avoid bundling unrelated concerns into one large script or component.

Validate end-to-end behavior

Run a smoke check through the critical path to confirm integration points.

tsx
1import React, { useRef } from 'react';
2import { View, Button } from 'react-native';
3
4export function MeasureDemo() {
5  const ref = useRef<View>(null);
6
7  const measureNow = () => {
8    ref.current?.measure((x, y, width, height, pageX, pageY) => {
9      console.log({ x, y, width, height, pageX, pageY });
10    });
11  };
12
13  return (
14    <View ref={ref} style={{ width: 180, height: 80 }}>
15      <Button title="Measure" onPress={measureNow} />
16    </View>
17  );
18}

Then add one failure-path test for the most probable operational error. This improves incident response because failure signatures are known before production rollout.

Operations and maintainability

Capture rollout steps and rollback commands near the implementation. Keep verification commands short and repeatable in both local and CI environments.

Add concise logs around decision boundaries with enough context for diagnosis. Avoid noisy logs with low actionability.

Document assumptions explicitly, such as version compatibility, lifecycle ordering, permission scope, and platform-specific rendering behavior. Explicit assumptions reduce maintenance drift.

Regression discipline

Add a focused regression test whenever a bug is fixed. This practice turns one-time troubleshooting into durable reliability and lowers repeated incident risk over time.

Release checklist and rollback readiness

Before merging or deploying, run one deterministic verification command in local development and in continuous integration. Compare outputs and record expected artifacts so deviations are easy to detect later. For platform-sensitive topics, include version identifiers in verification logs to make future comparisons meaningful.

Document rollback steps close to the implementation. A good rollback note includes the exact command, expected recovery signal, and any data-impact caveat. Clear rollback guidance reduces incident pressure and prevents risky improvisation.

Capture one known failure signature and map it to likely root causes. This small mapping dramatically speeds up triage when alerts fire, because responders can move directly from symptom to targeted diagnostics.

Common Pitfalls

  • Reading dimensions during initial render often yields zero before layout pass.
  • Using stale size state during orientation changes causes incorrect positioning.
  • Measuring off-screen or collapsed views returns misleading values.
  • Heavy work inside onLayout can trigger layout thrashing.
  • Assuming pixel values map directly across platforms can break UI consistency.

Summary

  • Use onLayout for reliable declarative size updates.
  • Use measure for imperative one-off reads after mount.
  • Recompute size-dependent logic on orientation or parent layout changes.
  • Keep layout callbacks lightweight to maintain smooth rendering.
  • Validate measurement behavior on both iOS and Android.

Related reading
Free course
Beginner
7 lessons
2 hours
Tackling System Design Interview Problems

A short course that equips you with the skills to approach system design interviews methodically.

Start the free course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

All Rights Reserved.