React Native Expoで画面描画速度の改善に取り組んで爆速になった話
はじめまして!株式会社HANOWAでエンジニアをしている榎本です。
今回は、React Native + Expoで開発しているモバイルアプリのパフォーマンス改善について、実際に行った施策と得られた知見を共有します。
はじめに
ハノワは、歯科医院と歯科医療従事者(歯科衛生士、歯科医師、歯科助手、歯科技工士)をつなぐマッチングプラットフォームです。
Webアプリケーションに加えて、iOS/Android向けのモバイルアプリを提供しています。
技術スタック
モバイルアプリは以下の技術スタックで開発しています。
- React Native 0.79.5
- Expo SDK 53
- TypeScript
- React 19
- Expo Router(ファイルベースルーティング)
React NativeとExpoの組み合わせにより、iOSとAndroidの両プラットフォームに対応したアプリを単一のコードベースで開発しています。
改善前の課題
アプリのリリース後、ユーザーから「動作が重い」「画面遷移が遅い」というフィードバックを受けることがありました。
特に深刻だったのが、タブ間の移動で酷い時には5秒以上かかるという問題です。
ホームタブから募集一覧タブに移動するだけで数秒待たされる。勤怠管理タブを開くと画面が固まったように感じる。このような状態は、ユーザー体験として致命的です。
ユーザーがアプリを使い続けてくれるかどうかは、こうした日常的な操作のレスポンスの良さにかかっています。たとえ機能が充実していても、毎回の画面遷移でストレスを感じるようでは、ユーザーは離れていってしまいます。
この問題を解決するため、パフォーマンス改善プロジェクトを開始しました。
パフォーマンス計測方法
パフォーマンス改善において最も重要なのは、推測ではなく計測に基づいて改善を行うことです。「なんとなく遅い気がする」という感覚だけで対策を打つと、効果のない箇所に時間を費やしてしまう可能性があります。
今回の改善では、React Developer ToolsのProfilerを中心に計測を行いました。
React DevTools Profilerとは
React DevTools Profilerは、Reactアプリケーションのレンダリングパフォーマンスを可視化するツールです。以下のような情報を確認できます。
- どのコンポーネントがレンダリングされたか
- 各コンポーネントのレンダリングにかかった時間
- なぜそのコンポーネントがレンダリングされたか(props変更、state変更、parent変更など)
- レンダリングの発生頻度
Profilerの具体的な使い方
1. 開発環境での準備
React Native + Expoの場合、以下の手順でProfilerを使用します。
- Expoの開発サーバーを起動
- React Native Debuggerまたはブラウザのデバッグツールを開く
- React DevToolsタブでProfilerを選択
- 「Record」ボタンを押してプロファイリングを開始
- アプリで問題のある操作を実行
- 「Stop」ボタンを押してプロファイリングを終了
2. レンダリング原因の特定
Profilerの「Why did this render?」機能を使うと、コンポーネントが再レンダリングされた理由を確認できます。
主な原因は以下の4つです。
| 原因 | 説明 |
|---|---|
| Props changed | propsが変更された |
| State changed | stateが変更された |
| Context changed | 使用しているContextの値が変更された |
| Parent rendered | 親コンポーネントが再レンダリングされた |
特に「Parent rendered」が頻発している場合は、React.memoによる最適化が効果的です。
3. パフォーマンスボトルネックの発見
Profilerのフレームグラフを見ると、レンダリングに時間がかかっているコンポーネントが一目でわかります。色が濃いほどレンダリング時間が長いことを示しています。
今回の調査では、以下のような問題が発見されました。
- タブを切り替えるたびに、表示していないタブのコンポーネントまで再レンダリングされている
- リスト表示で、1つのアイテムの状態が変わると全アイテムが再レンダリングされている
- モーダルを開閉するたびに、背面のコンポーネントが再レンダリングされている
計測時の注意点:リリースビルドでテストする
開発モード(__DEV__ === true)では、以下の理由でパフォーマンスが大幅に低下します。
- 開発用の警告やエラーチェックが有効
- ホットリロードのためのコードが含まれる
- ソースマップの生成などのオーバーヘッド
開発モードで「遅い」と感じても、リリースビルドでは問題ない場合があります。逆に、開発モードで気づかなかったパフォーマンス問題がリリースビルドで顕在化することもあります。
原因の特定:NativeBaseのパフォーマンス問題
Profilerを使った調査の結果、NativeBaseがパフォーマンスのボトルネックになっていることがわかりました。
NativeBaseとは
NativeBaseは、React Native向けの人気のあるUIコンポーネントライブラリです。
以下のような特徴があります。
- Box、Text、Buttonなど、多数の汎用コンポーネントを提供
- レスポンシブデザインのサポート
- テーマのカスタマイズ機能
- アクセシビリティへの配慮
開発初期には、これらの機能が開発効率の向上に貢献していました。しかし、アプリが成長するにつれて、パフォーマンスの問題が顕在化してきました。
注意:NativeBaseは現在メンテナンスされていません。 公式からも後継ライブラリであるgluestack-uiへの移行が推奨されています。新規プロジェクトでNativeBaseを採用することは避けるべきです。
NativeBaseのパフォーマンス問題
調査の結果、以下の問題が明らかになりました。
1. スタイル計算のオーバーヘッド
NativeBaseは、プロパティベースのスタイリングシステムを採用しています。
// NativeBaseのスタイリング例
<Box mt={4} px={2} bg="primary.500" borderRadius="lg">
<Text fontSize="md" fontWeight="bold" color="white">
Hello
</Text>
</Box>
この便利な記法の裏側では、毎回のレンダリング時にスタイルオブジェクトの生成と変換が行われています。コンポーネント数が増えると、このオーバーヘッドが累積して無視できないレベルになります。
2. 内部的なContext依存
NativeBaseは、テーマやカラーモードなどの機能を実現するために、内部的に複数のContextを使用しています。これにより、Contextの値が変更されると、NativeBaseコンポーネントを使用している広範囲のコンポーネントが再レンダリングされてしまいます。
3. バンドルサイズの肥大化
NativeBaseをインストールすると、使っていない機能も含めてバンドルに含まれます。これはアプリの初期ロード時間に影響を与えます。
4. 依存関係の複雑さ
NativeBaseは多くの依存パッケージを持っています。yarn.lockを確認すると、NativeBase関連のパッケージだけで1000行以上を占めていました。これらの依存関係がパフォーマンスに影響を与えている可能性もありました。
改善方針の検討
NativeBaseのパフォーマンス問題に対して、いくつかの改善方針を検討しました。
| 方針 | メリット | デメリット |
|---|---|---|
| NativeBaseの最適化設定を調整 | 影響範囲が小さい | 根本的な解決にならない |
| 部分的に自前コンポーネントに置き換え | 段階的に進められる | 混在状態が続く |
| NativeBaseを完全に削除 | 根本的な解決 | 工数が大きい |
様々な最適化を試みましたが、NativeBaseを使い続ける限り、根本的なパフォーマンス改善は難しいという結論に達しました。
最終的に、NativeBaseからの完全な脱却を決断しました。
実施した改善施策
NativeBaseからの移行は大規模なリファクタリングとなりました。合計45個のPRを作成し、約1ヶ月かけて段階的にNativeBaseを置き換えました。
安全に移行を進めるため、以下の方針で進めました。
- コンポーネント単位で段階的に移行:一度にすべてを変更するのではなく、Text、Button、Boxなど、コンポーネント単位でPRを分割
- 十分なテスト期間を確保:各PRをマージ後、テスト環境で動作確認
- ロールバック可能な状態を維持:問題が発生した場合に備えて、元の状態に戻せるようにする
1. 自前コンポーネントへの移行
NativeBaseのコンポーネントを、React Nativeの標準コンポーネントをベースにした自前コンポーネントに置き換えました。
移行したコンポーネント一覧
移行したコンポーネントは多岐にわたります。
| カテゴリ | NativeBaseコンポーネント | 移行先 |
|---|---|---|
| レイアウト | Box, HStack, VStack, Flex, Center | 自前コンポーネント |
| テキスト | Text, Heading | 自前コンポーネント |
| フォーム | Input, Button, Checkbox, Radio, Switch, FormControl | 自前コンポーネント |
| フィードバック | Spinner, Badge | 自前コンポーネント |
| メディア | Image, Avatar | 自前コンポーネント |
| ナビゲーション | Link | React Native標準 |
| その他 | Divider, Icon, IconButton, AspectRatio | 自前コンポーネント |
| リスト系 | FlatList, SectionList, ScrollView | React Native標準 |
| 基本要素 | View, Pressable, StatusBar | React Native標準 |
設計方針
自前コンポーネントを設計する際、以下の方針を採用しました。
- シンプルさを最優先:NativeBaseの便利機能をすべて再現するのではなく、実際に使っている機能だけを実装
- React.memoをデフォルトで適用:すべてのコンポーネントを最初からメモ化
- React NativeのStyleSheetを直接使用:スタイル変換のオーバーヘッドを排除
- TypeScriptによる型安全性:ViewStyleやTextStyleの型を活用し、無効なスタイルプロパティを検出
- 呼び出し側でのメモ化を前提とする:カスタム比較関数は使わず、デフォルトのshallow comparisonを使用
Boxコンポーネントの実装
最も使用頻度の高いレイアウトコンポーネントBoxの実装を詳しく見てみましょう。
// src/components/ui/Box.tsx
import React, { memo } from 'react';
import { View, ViewProps, ViewStyle } from 'react-native';
export type Props = {
// サイズ関連
width?: ViewStyle['width'];
minWidth?: ViewStyle['minWidth'];
maxWidth?: ViewStyle['maxWidth'];
height?: ViewStyle['height'];
minHeight?: ViewStyle['minHeight'];
maxHeight?: ViewStyle['maxHeight'];
// Flexbox関連
flex?: ViewStyle['flex'];
flexDirection?: ViewStyle['flexDirection'];
flexWrap?: ViewStyle['flexWrap'];
flexGrow?: ViewStyle['flexGrow'];
flexShrink?: ViewStyle['flexShrink'];
// スペーシング関連
padding?: ViewStyle['padding'];
paddingHorizontal?: ViewStyle['paddingHorizontal'];
paddingVertical?: ViewStyle['paddingVertical'];
paddingTop?: ViewStyle['paddingTop'];
paddingBottom?: ViewStyle['paddingBottom'];
paddingLeft?: ViewStyle['paddingLeft'];
paddingRight?: ViewStyle['paddingRight'];
margin?: ViewStyle['margin'];
marginHorizontal?: ViewStyle['marginHorizontal'];
marginVertical?: ViewStyle['marginVertical'];
marginTop?: ViewStyle['marginTop'];
marginBottom?: ViewStyle['marginBottom'];
marginLeft?: ViewStyle['marginLeft'];
marginRight?: ViewStyle['marginRight'];
// 配置関連
alignSelf?: ViewStyle['alignSelf'];
alignItems?: ViewStyle['alignItems'];
justifyContent?: ViewStyle['justifyContent'];
gap?: ViewStyle['gap'];
// 装飾関連
backgroundColor?: ViewStyle['backgroundColor'];
borderWidth?: ViewStyle['borderWidth'];
borderTopWidth?: ViewStyle['borderTopWidth'];
borderBottomWidth?: ViewStyle['borderBottomWidth'];
borderColor?: ViewStyle['borderColor'];
borderRadius?: ViewStyle['borderRadius'];
// その他
style?: ViewProps['style'];
children?: ViewProps['children'];
};
function BoxImpl({
width,
minWidth,
maxWidth,
height,
minHeight,
maxHeight,
flex,
flexDirection,
flexWrap,
flexGrow,
flexShrink,
padding,
paddingHorizontal,
paddingVertical,
paddingTop,
paddingBottom,
paddingLeft,
paddingRight,
margin,
marginHorizontal,
marginVertical,
marginTop,
marginBottom,
marginLeft,
marginRight,
alignSelf,
alignItems,
justifyContent,
gap,
backgroundColor,
borderWidth,
borderTopWidth,
borderBottomWidth,
borderColor,
borderRadius,
style,
children,
}: Props) {
return (
<View
style={[
// 各プロパティがundefinedでない場合のみスタイルに含める
width !== undefined && { width },
minWidth !== undefined && { minWidth },
maxWidth !== undefined && { maxWidth },
height !== undefined && { height },
minHeight !== undefined && { minHeight },
maxHeight !== undefined && { maxHeight },
flex !== undefined && { flex },
flexDirection !== undefined && { flexDirection },
flexWrap !== undefined && { flexWrap },
flexGrow !== undefined && { flexGrow },
flexShrink !== undefined && { flexShrink },
padding !== undefined && { padding },
paddingHorizontal !== undefined && { paddingHorizontal },
paddingVertical !== undefined && { paddingVertical },
paddingTop !== undefined && { paddingTop },
paddingBottom !== undefined && { paddingBottom },
paddingLeft !== undefined && { paddingLeft },
paddingRight !== undefined && { paddingRight },
margin !== undefined && { margin },
marginHorizontal !== undefined && { marginHorizontal },
marginVertical !== undefined && { marginVertical },
marginTop !== undefined && { marginTop },
marginBottom !== undefined && { marginBottom },
marginLeft !== undefined && { marginLeft },
marginRight !== undefined && { marginRight },
alignSelf !== undefined && { alignSelf },
alignItems !== undefined && { alignItems },
justifyContent !== undefined && { justifyContent },
gap !== undefined && { gap },
backgroundColor !== undefined && { backgroundColor },
borderWidth !== undefined && { borderWidth },
borderTopWidth !== undefined && { borderTopWidth },
borderBottomWidth !== undefined && { borderBottomWidth },
borderColor !== undefined && { borderColor },
borderRadius !== undefined && { borderRadius },
style,
]}>
{children}
</View>
);
}
// React.memoでラップして不要な再レンダリングを防止
export const Box = memo(BoxImpl);
Box.displayName = 'Box';
設計のポイント:
-
条件付きスタイル適用:
width !== undefined && { width }というパターンで、指定されたプロパティのみをスタイルに含めています。これにより、不要なスタイルプロパティが含まれることを防ぎます。 -
型安全性:
ViewStyle['width']のように、React NativeのViewStyle型を参照することで、無効な値を渡すとTypeScriptエラーになります。 -
displayNameの設定:デバッグ時にコンポーネント名が表示されるよう、displayNameを設定しています。
HStackとVStackの実装
横並び(HStack)と縦並び(VStack)のレイアウトコンポーネントは、Boxを継承してシンプルに実装しました。
// src/components/ui/HStack.tsx
import React, { memo } from 'react';
import { Box, Props as BoxProps } from './Box';
// flexDirectionは固定なので、propsから除外
type Props = Omit<BoxProps, 'flexDirection'>;
function HStackImpl({ children, ...props }: Props) {
return (
<Box flexDirection="row" {...props}>
{children}
</Box>
);
}
export const HStack = memo(HStackImpl);
HStack.displayName = 'HStack';
// src/components/ui/VStack.tsx
import React, { memo } from 'react';
import { Box, Props as BoxProps } from './Box';
type Props = Omit<BoxProps, 'flexDirection'>;
function VStackImpl({ children, ...props }: Props) {
// VStackはflexDirection: 'column'がデフォルトなので、明示的な指定は不要
return <Box {...props}>{children}</Box>;
}
export const VStack = memo(VStackImpl);
VStack.displayName = 'VStack';
このように、基本となるBoxコンポーネントを作成し、それを継承する形でHStack/VStackを実装することで、コードの重複を避けつつ、一貫した動作を保証しています。
Textコンポーネントの実装
Textコンポーネントでは、lineHeightのem単位サポートなど、NativeBaseで使っていた便利機能を一部再現しています。
// src/components/ui/Text.tsx
import React, { memo } from 'react';
import { Text as RNText, TextProps as RNTextProps, StyleSheet, TextStyle } from 'react-native';
import colors from '@/styles/Colors';
const DEFAULT_FONT_SIZE = 14;
type Props = {
fontSize?: number;
fontWeight?: TextStyle['fontWeight'];
lineHeight?: number | `${number}em`; // em単位もサポート
color?: string;
textAlign?: TextStyle['textAlign'];
textDecorationLine?: TextStyle['textDecorationLine'];
alignSelf?: TextStyle['alignSelf'];
flex?: TextStyle['flex'];
flexShrink?: TextStyle['flexShrink'];
numberOfLines?: RNTextProps['numberOfLines'];
ellipsizeMode?: RNTextProps['ellipsizeMode'];
onPress?: RNTextProps['onPress'];
accessibilityRole?: RNTextProps['accessibilityRole'];
style?: RNTextProps['style'];
children?: React.ReactNode;
};
// 静的なスタイルはStyleSheet.createで事前に定義
const styles = StyleSheet.create({
base: {
fontSize: DEFAULT_FONT_SIZE,
fontWeight: '400',
lineHeight: 15,
color: colors.text.black,
},
});
// lineHeightの解決ロジック
function resolveLineHeight(lineHeight: Props['lineHeight'], fontSize: number): number | undefined {
if (lineHeight === undefined) {
// デフォルト: 1.5em
return fontSize * 1.5;
}
if (typeof lineHeight === 'number') {
return lineHeight;
} else if (lineHeight.endsWith('em')) {
// "1.5em" のような文字列を解析
const n = parseFloat(lineHeight);
return isNaN(n) ? fontSize * 1.5 : n * fontSize;
}
return undefined;
}
function TextImpl({
fontSize = DEFAULT_FONT_SIZE,
fontWeight,
lineHeight,
color,
textAlign,
textDecorationLine,
alignSelf,
flex,
flexShrink,
numberOfLines,
ellipsizeMode,
onPress,
accessibilityRole,
style,
children,
}: Props) {
const resolvedLineHeight = resolveLineHeight(lineHeight, fontSize);
return (
<RNText
numberOfLines={numberOfLines}
ellipsizeMode={ellipsizeMode}
onPress={onPress}
accessibilityRole={accessibilityRole}
style={[
styles.base,
fontSize !== undefined && { fontSize },
fontWeight !== undefined && { fontWeight },
resolvedLineHeight !== undefined && { lineHeight: resolvedLineHeight },
color !== undefined && { color },
textAlign !== undefined && { textAlign },
textDecorationLine !== undefined && { textDecorationLine },
alignSelf !== undefined && { alignSelf },
flex !== undefined && { flex },
flexShrink !== undefined && { flexShrink },
style,
]}>
{children}
</RNText>
);
}
// デフォルトのshallow comparisonを使用
// 呼び出し側でstyleやonPressを適切にメモ化することを前提とする
export const Text = memo(TextImpl);
Text.displayName = 'Text';
カスタム比較関数をやめた理由
当初、TextコンポーネントなどではReact.memoの第2引数にカスタム比較関数を渡していました。
// ❌ 当初の実装:カスタム比較関数
export const Text = memo(TextImpl, (prev, next) => {
return (
prev.fontSize === next.fontSize &&
prev.fontWeight === next.fontWeight &&
prev.lineHeight === next.lineHeight &&
prev.color === next.color &&
// ... 全propsを比較
prev.children === next.children
);
});
しかし、この方法には以下の問題がありました。
- メンテナンスコストが高い:propsが追加されるたびに比較関数も更新が必要
- バグの温床になる:比較関数の更新漏れで、propsが変わっても再レンダリングされない問題が発生しうる
- 責任の所在が曖昧:コンポーネント側と呼び出し側のどちらがメモ化の責任を持つか不明確
そこで、呼び出し側でのメモ化を徹底する方針に切り替えました。
// ✅ 現在の実装:デフォルトのshallow comparisonを使用
export const Text = memo(TextImpl);
呼び出し側での徹底事項:
- styleは
StyleSheet.createで事前に定義 - onPressなどのコールバックは
useCallbackでメモ化 - オブジェクトや配列は
useMemoでメモ化
// ✅ 呼び出し側でのメモ化を徹底
const MyComponent = () => {
// styleはコンポーネント外でStyleSheet.createで定義
// または、動的な場合はuseMemoでメモ化
const handlePress = useCallback(() => {
// 処理
}, []);
return (
<Text
fontSize={16}
color={colors.text.black}
onPress={handlePress} // useCallbackでメモ化済み
style={styles.text} // StyleSheet.createで定義済み
>
テキスト
</Text>
);
};
// コンポーネント外で定義
const styles = StyleSheet.create({
text: {
marginTop: 8,
},
});
この方針により、以下のメリットが得られました。
- シンプルなコンポーネント実装:カスタム比較関数の管理が不要
- 明確な責任分担:メモ化の責任は呼び出し側にある
- 一貫したコーディングルール:チーム全体で同じルールを適用しやすい
Buttonコンポーネントの実装
Buttonコンポーネントは、バリアント(primary、secondary、danger等)やサイズ(large、medium、small)のサポートが必要な複雑なコンポーネントです。
// src/components/ui/Button.tsx
import React, { memo } from 'react';
import {
ActivityIndicator,
Pressable,
PressableProps,
StyleSheet,
Text,
TextStyle,
View,
ViewStyle,
} from 'react-native';
import colors from '@/styles/Colors';
export type Props = {
variant?: 'primary' | 'secondary' | 'danger' | 'tertiary' | 'warning' | 'base';
size?: 'large' | 'medium' | 'small';
disabled?: boolean;
isLoading?: boolean;
onPress?: PressableProps['onPress'];
leftIcon?: React.ReactNode;
rightIcon?: React.ReactNode;
flex?: ViewStyle['flex'];
flexShrink?: ViewStyle['flexShrink'];
width?: ViewStyle['width'];
maxWidth?: ViewStyle['maxWidth'];
alignSelf?: ViewStyle['alignSelf'];
marginTop?: ViewStyle['marginTop'];
marginBottom?: ViewStyle['marginBottom'];
marginLeft?: ViewStyle['marginLeft'];
marginRight?: ViewStyle['marginRight'];
margin?: ViewStyle['margin'];
textNumberOfLines?: number;
style?: ViewStyle;
textStyle?: TextStyle;
children?: React.ReactNode;
};
// バリアントとdisabled状態に応じた色を取得
const getColors = (
variant: Props['variant'],
disabled: Props['disabled'],
isLoading: Props['isLoading']
) => {
if (disabled && !isLoading) {
switch (variant) {
case 'primary':
return {
backgroundColor: colors.main.primary,
textColor: colors.text.white,
opacity: 0.3,
};
default:
return {
backgroundColor: colors.background.disabled,
textColor: colors.text.disabledBackground,
opacity: 1,
};
}
}
switch (variant) {
case 'secondary':
return {
backgroundColor: colors.background.primary,
textColor: colors.text.primaryBackground,
opacity: 1,
};
case 'tertiary':
return {
backgroundColor: colors.background.base,
textColor: colors.text.black,
opacity: 1,
};
case 'danger':
return {
backgroundColor: colors.support.red,
textColor: colors.main.white,
opacity: 1,
};
case 'warning':
return {
backgroundColor: colors.background.error,
textColor: colors.text.errorBackground,
opacity: 1,
};
case 'base':
return {
backgroundColor: colors.background.base,
textColor: colors.text.black,
opacity: 1,
};
default:
return {
backgroundColor: colors.main.primary,
textColor: colors.main.white,
opacity: 1,
};
}
};
// サイズに応じたパディングとフォントサイズを取得
const getSize = (size: Props['size'], hasLeftIcon: boolean, hasRightIcon: boolean) => {
switch (size) {
case 'medium':
return {
paddingLeft: hasLeftIcon ? 8 : 12,
paddingRight: hasRightIcon ? 8 : 12,
paddingVertical: 10,
fontSize: 14,
lineHeight: 20,
gap: 4,
};
case 'small':
return {
paddingLeft: hasLeftIcon ? 6 : 8,
paddingRight: hasRightIcon ? 6 : 8,
paddingVertical: 10,
fontSize: 12,
lineHeight: 18,
gap: 2,
};
default: // large
return {
paddingLeft: hasLeftIcon ? 12 : 16,
paddingRight: hasRightIcon ? 12 : 16,
paddingVertical: 10,
fontSize: 16,
lineHeight: 22,
gap: 4,
};
}
};
function ButtonImpl({
variant = 'primary',
size = 'large',
disabled = false,
isLoading = false,
onPress,
leftIcon,
rightIcon,
flex,
flexShrink,
width,
maxWidth,
alignSelf,
marginTop,
marginBottom,
marginLeft,
marginRight,
margin,
textNumberOfLines,
style,
textStyle,
children,
}: Props) {
const { backgroundColor, textColor, opacity } = getColors(variant, disabled, isLoading);
const { paddingLeft, paddingRight, paddingVertical, fontSize, lineHeight, gap } = getSize(
size,
!!leftIcon,
!!rightIcon
);
return (
<Pressable
disabled={disabled || isLoading}
onPress={onPress}
style={({ pressed }) => [
styles.base,
{
paddingLeft,
paddingRight,
paddingVertical,
backgroundColor,
// 押下時は透明度を下げてフィードバック
opacity: pressed ? opacity * 0.8 : opacity,
gap,
},
flex !== undefined && { flex },
flexShrink !== undefined && { flexShrink },
width !== undefined && { width },
maxWidth !== undefined && { maxWidth },
alignSelf !== undefined && { alignSelf },
marginTop !== undefined && { marginTop },
marginBottom !== undefined && { marginBottom },
marginLeft !== undefined && { marginLeft },
marginRight !== undefined && { marginRight },
margin !== undefined && { margin },
style,
]}>
{isLoading ? (
// ローディング中はActivityIndicatorを表示
<ActivityIndicator size="small" color={textColor} />
) : (
<>
{leftIcon && <View>{leftIcon}</View>}
{typeof children === 'string' ? (
<Text
numberOfLines={textNumberOfLines}
style={[
styles.text,
{
fontSize,
lineHeight,
color: textColor,
},
textStyle,
]}>
{children}
</Text>
) : (
children
)}
{rightIcon && <View>{rightIcon}</View>}
</>
)}
</Pressable>
);
}
export const Button = memo(ButtonImpl);
Button.displayName = 'Button';
const styles = StyleSheet.create({
base: {
flexDirection: 'row',
justifyContent: 'center',
alignItems: 'center',
borderRadius: 999, // 完全な角丸
},
text: {
fontWeight: '600',
flexShrink: 1, // 長いテキストを省略可能に
},
});
2. ActionSheetからBottomSheetModalへの移行
NativeBaseのActionsheetコンポーネントは、画面下部からスライドして表示されるモーダルです。これを@gorhom/bottom-sheetライブラリに移行しました。
なぜ@gorhom/bottom-sheetを選んだか
いくつかのライブラリを比較検討した結果、以下の理由で@gorhom/bottom-sheetを選択しました。
| ライブラリ | メリット | デメリット |
|---|---|---|
| @gorhom/bottom-sheet | ネイティブドライバー対応、高いカスタマイズ性、活発なメンテナンス | 学習コストがやや高い |
| react-native-modal | シンプル、使いやすい | ジェスチャー対応が限定的 |
| react-native-modalize | 機能が豊富 | メンテナンスが停滞気味 |
特に、ネイティブドライバー(Reanimated)によるスムーズなアニメーションが決め手となりました。
セットアップ
@gorhom/bottom-sheetを使用するには、いくつかの依存パッケージが必要です。
yarn add @gorhom/bottom-sheet react-native-reanimated react-native-gesture-handler
babel.config.jsにReanimatedのプラグインを追加します。
// babel.config.js
module.exports = function(api) {
api.cache(true);
return {
presets: ['babel-preset-expo'],
plugins: [
'react-native-reanimated/plugin', // 必ず最後に追加
],
};
};
アプリのルートコンポーネントをGestureHandlerRootViewとBottomSheetModalProviderでラップします。
// src/app/_layout.tsx
import { BottomSheetModalProvider } from '@gorhom/bottom-sheet';
import { GestureHandlerRootView } from 'react-native-gesture-handler';
const RootLayout = () => {
return (
<GestureHandlerRootView style={{ flex: 1 }}>
<BottomSheetModalProvider>
{/* アプリのコンテンツ */}
</BottomSheetModalProvider>
</GestureHandlerRootView>
);
};
自前のModalコンポーネントの実装
BottomSheetModalをラップした、使いやすいModalコンポーネントを作成しました。
// src/components/ui/Modal.tsx
import {
BottomSheetModal,
BottomSheetModalProps,
BottomSheetBackdrop,
BottomSheetScrollView,
type BottomSheetBackdropProps,
} from '@gorhom/bottom-sheet';
import React, { forwardRef, memo, useCallback, useMemo } from 'react';
import { StyleSheet } from 'react-native';
import { useSafeAreaInsets } from 'react-native-safe-area-context';
import { BaseModalHeader } from '@/components/modals';
import { Box, Button, Divider, HStack } from '@/components/ui';
import { Props as ButtonProps } from '@/components/ui/Button';
export type Props = BottomSheetModalProps & {
title?: string;
onClose: () => void;
headerActionProps?: { label: string } & Omit<ButtonProps, 'children'>;
submitProps?: { label: string } & Omit<ButtonProps, 'children'>;
resetProps?: { label: string } & Omit<ButtonProps, 'children'>;
footerContent?: React.ReactNode;
children: React.ReactNode;
};
const ModalImpl = forwardRef<BottomSheetModal, Props>(
(
{ title, onClose, headerActionProps, submitProps, resetProps, footerContent, children },
ref
) => {
const { top, bottom } = useSafeAreaInsets();
// 背景のオーバーレイをカスタマイズ
const renderBackdrop = useCallback(
(props: BottomSheetBackdropProps) => (
<BottomSheetBackdrop
{...props}
disappearsOnIndex={-1}
appearsOnIndex={0}
opacity={0.5}
pressBehavior="collapse"
onPress={onClose}
/>
),
[onClose]
);
// SafeAreaを考慮したスタイル
const dynamicStyles = useMemo(
() =>
StyleSheet.create({
contentContainer: {
paddingBottom: bottom,
},
}),
[bottom]
);
return (
<BottomSheetModal
ref={ref}
topInset={top} // ノッチを考慮
backdropComponent={renderBackdrop}
stackBehavior="push" // 複数モーダルをスタック可能
keyboardBlurBehavior="restore"
enableContentPanningGesture={false}
enableHandlePanningGesture={false}
enableOverDrag={false}
enablePanDownToClose={false}
handleIndicatorStyle={styles.indicator}>
<BottomSheetScrollView contentContainerStyle={dynamicStyles.contentContainer}>
{/* ヘッダー */}
{(title || headerActionProps) && (
<BaseModalHeader
title={title}
onClose={onClose}
headerActionProps={headerActionProps}
/>
)}
{/* コンテンツ */}
<Box width="100%" paddingVertical={16}>
{children}
</Box>
{/* フッター */}
{footerContent}
{(resetProps || submitProps) && (
<>
{!footerContent && (
<Box width="100%" marginVertical={16}>
<Divider />
</Box>
)}
<Box paddingHorizontal={16} width="100%">
<HStack width="100%" paddingBottom={8} gap={8}>
{resetProps && (
<Button {...resetProps} flex={resetProps.flex ?? 1}>
{resetProps.label}
</Button>
)}
{submitProps && (
<Button {...submitProps} flex={submitProps.flex ?? 1}>
{submitProps.label}
</Button>
)}
</HStack>
</Box>
</>
)}
</BottomSheetScrollView>
</BottomSheetModal>
);
}
);
ModalImpl.displayName = 'Modal';
export const Modal = memo(ModalImpl);
const styles = StyleSheet.create({
indicator: {
backgroundColor: 'transparent',
},
});
使用例
状態管理がstateベースからrefベースに変わります。
// Before: NativeBase Actionsheet(stateベース)
const [isOpen, setIsOpen] = useState(false);
<Actionsheet isOpen={isOpen} onClose={() => setIsOpen(false)}>
<Actionsheet.Content>
{/* コンテンツ */}
</Actionsheet.Content>
</Actionsheet>
<Button onPress={() => setIsOpen(true)}>開く</Button>
// After: @gorhom/bottom-sheet(refベース)
const modalRef = useRef<BottomSheetModal>(null);
const handleOpen = useCallback(() => {
modalRef.current?.present();
}, []);
const handleClose = useCallback(() => {
modalRef.current?.dismiss();
}, []);
<Modal
ref={modalRef}
title="タイトル"
onClose={handleClose}
submitProps={{ label: '保存', onPress: handleSubmit }}
>
{/* コンテンツ */}
</Modal>
<Button onPress={handleOpen}>開く</Button>
refベースのメリット:
- stateの変更による再レンダリングが発生しない:モーダルの開閉がstateに依存しないため、親コンポーネントの再レンダリングを防げます
-
命令的な制御が可能:
present()やdismiss()メソッドで直接制御できます - アニメーションの制御がしやすい:snapToIndexなどでアニメーションを細かく制御できます
BottomSheet内でのTextInput対応
BottomSheetModal内でTextInputを使用する場合、特別な対応が必要です。通常のTextInputではキーボードが正しく動作しない場合があるため、BottomSheetTextInputを使用します。
// src/components/ui/TextInput.tsx
type Variant = 'default' | 'bottom-sheet';
type Props = {
variant?: Variant;
// ... その他のprops
};
const TextInputImpl = forwardRef<RNTextInput, Props>(({ variant = 'default', ...props }, ref) => {
// variantに応じてコンポーネントを切り替え
const InputComponent =
variant === 'bottom-sheet'
? require('@gorhom/bottom-sheet').BottomSheetTextInput
: RNTextInput;
return <InputComponent ref={ref} {...props} />;
});
3. ToastをReact Native Toast Messageへ移行
NativeBaseのtoastをreact-native-toast-messageに移行しました。
移行の背景
NativeBaseのtoastには以下の問題がありました。
- モーダルの背面に表示される:React NativeのModalを使用している場合、toastがモーダルの背面に隠れてしまう
- スタイリングの自由度が低い:デザインのカスタマイズに制限がある
- Androidでの挙動が不安定:プラットフォームによって動作が異なる
カスタムToastコンポーネントの実装
react-native-toast-messageでは、カスタムのtoastコンポーネントを定義できます。
// src/components/toast/Toast.tsx
import { type FC } from 'react';
import { Dimensions, StyleSheet } from 'react-native';
import { Box, Text } from '@/components/ui';
import colors from '@/styles/Colors';
type Props = {
type: 'success' | 'error';
message: string | undefined;
};
const windowWidth = Dimensions.get('window').width;
export const Toast: FC<Props> = ({ type, message }) => (
<Box width={windowWidth} paddingHorizontal={16}>
<Box style={styles.container}>
<Box
style={styles.inner}
paddingVertical={12}
paddingHorizontal={16}
backgroundColor={type === 'success' ? colors.background.primary : colors.background.error}
borderRadius={8}>
<Text fontSize={14} fontWeight="300" color={colors.text.black} textAlign="left">
{message}
</Text>
</Box>
</Box>
</Box>
);
const styles = StyleSheet.create({
container: {
// 外側のシャドウ
shadowColor: '#000',
shadowOffset: { width: 0, height: 10 },
shadowOpacity: 0.1,
shadowRadius: 15,
elevation: 10,
},
inner: {
// 内側のシャドウ
shadowColor: '#000',
shadowOffset: { width: 0, height: 4 },
shadowOpacity: 0.05,
shadowRadius: 6,
elevation: 4,
},
});
アプリへの組み込み
// src/app/_layout.tsx
import Toast, { type ToastShowParams } from 'react-native-toast-message';
import { Toast as CustomToast } from '@/components/toast';
// カスタムtoast設定
const toastConfig = {
success: ({ text1 }: ToastShowParams) => <CustomToast type="success" message={text1} />,
error: ({ text1 }: ToastShowParams) => <CustomToast type="error" message={text1} />,
};
const RootLayout = () => {
return (
<GestureHandlerRootView style={{ flex: 1 }}>
<SafeAreaProvider>
<BottomSheetModalProvider>
{/* アプリのコンテンツ */}
</BottomSheetModalProvider>
{/* Toastはアプリの最上位に配置 */}
<Toast config={toastConfig} />
</SafeAreaProvider>
</GestureHandlerRootView>
);
};
useToastフックの実装
toastの表示を簡単に行えるカスタムフックを作成しました。
// src/hooks/useToast.tsx
import { Platform, ToastAndroid } from 'react-native';
import Toast from 'react-native-toast-message';
const isAndroid = Platform.OS === 'android';
type ToastType = 'success' | 'error';
interface ToastOptions {
type: ToastType;
message: string;
}
export const useToast = () => {
const show = ({ type, message }: ToastOptions) => {
// Androidではネイティブのトーストを使用
// これにより、モーダル表示中でも確実にトーストが表示される
if (isAndroid) {
ToastAndroid.show(message, ToastAndroid.LONG);
return;
}
// iOSではreact-native-toast-messageを使用
Toast.show({
type,
text1: message,
position: 'bottom',
visibilityTime: 2500,
});
};
return { show };
};
プラットフォーム別の対応理由:
Androidでは、BottomSheetModalを使用している状態でreact-native-toast-messageのtoastを表示すると、z-indexの問題でtoastがモーダルの背面に隠れてしまうことがあります。この問題を回避するため、AndroidではOSネイティブのToastAndroidを使用しています。
NativeBaseの完全削除
toastの移行が完了したことで、NativeBaseのすべての機能の移行が完了しました。package.jsonからNativeBaseを削除します。
// package.json
{
"dependencies": {
- "native-base": "^3.4.28",
+ "react-native-toast-message": "^2.3.3",
},
"devDependencies": {
- "patch-package": "^8.0.0",
}
}
yarn.lockの変化は劇的でした。
# yarn.lock
- 1052行削減
+ 12行追加
NativeBase関連の依存パッケージがすべて削除され、yarn.lockが大幅にスリム化されました。
4. コンポーネントのメモ化(React.memo + useCallback)
自前コンポーネントへの移行と並行して、既存コンポーネントの再レンダリング最適化も行いました。
問題のあるコード例
以下のようなコードは、パフォーマンス上の問題があります。
// ❌ 問題のあるコード
const ParentComponent = () => {
const [count, setCount] = useState(0);
const [items, setItems] = useState<Item[]>([]);
// 問題1: handlePressが毎回新しい関数として作成される
const handlePress = (id: string) => {
console.log(id);
};
// 問題2: filteredItemsが毎回新しい配列として作成される
const filteredItems = items.filter(item => item.active);
return (
<View>
<Text>Count: {count}</Text>
<Button onPress={() => setCount(c => c + 1)} title="Increment" />
{/* 問題3: countが変わるたびに全ItemCardが再レンダリングされる */}
{filteredItems.map(item => (
<ItemCard
key={item.id}
item={item}
onPress={handlePress}
/>
))}
</View>
);
};
// 問題4: ItemCardがメモ化されていない
const ItemCard = ({ item, onPress }) => {
return (
<Pressable onPress={() => onPress(item.id)}>
<Text>{item.name}</Text>
</Pressable>
);
};
このコードには4つの問題があります。
-
handlePressが毎回新しい関数として作成される -
filteredItemsが毎回新しい配列として作成される -
countが変わるとすべてのItemCardが再レンダリングされる -
ItemCardがメモ化されていない
改善後のコード
// ✅ 改善後のコード
const ParentComponent = () => {
const [count, setCount] = useState(0);
const [items, setItems] = useState<Item[]>([]);
// 改善1: useCallbackで関数をメモ化
const handlePress = useCallback((id: string) => {
console.log(id);
}, []);
// 改善2: useMemoで計算結果をメモ化
const filteredItems = useMemo(
() => items.filter(item => item.active),
[items]
);
// 改善: setCountにuseCallbackは不要(setStateは安定した参照)
const handleIncrement = useCallback(() => {
setCount(c => c + 1);
}, []);
return (
<View>
<Text>Count: {count}</Text>
<Button onPress={handleIncrement} title="Increment" />
{/* countが変わってもItemCardは再レンダリングされない */}
{filteredItems.map(item => (
<ItemCard
key={item.id}
item={item}
onPress={handlePress}
/>
))}
</View>
);
};
// 改善4: React.memoでコンポーネントをメモ化
const ItemCard = memo(({ item, onPress }: ItemCardProps) => {
// 改善: インラインの関数呼び出しをuseCallbackでラップ
const handleItemPress = useCallback(() => {
onPress(item.id);
}, [onPress, item.id]);
return (
<Pressable onPress={handleItemPress}>
<Text>{item.name}</Text>
</Pressable>
);
});
React.memoとuseCallbackの関係
React.memoとuseCallbackは、セットで使わないと効果が薄いことを理解することが重要です。
// ❌ useCallbackなしでReact.memoを使っても効果が薄い
const Parent = () => {
const handlePress = () => {}; // 毎回新しい関数
return <Child onPress={handlePress} />; // propsが変わったと判定される
};
const Child = memo(({ onPress }) => {
// React.memoがあっても、onPressの参照が毎回変わるので再レンダリングされる
});
// ✅ useCallbackと組み合わせて初めて効果を発揮
const Parent = () => {
const handlePress = useCallback(() => {}, []); // 同じ参照が維持される
return <Child onPress={handlePress} />; // propsが変わらないと判定される
};
const Child = memo(({ onPress }) => {
// 親が再レンダリングされても、propsが変わらないので再レンダリングされない
});
5. FlatListのパフォーマンス改善
React Nativeでリストを表示する際、FlatListのパフォーマンス最適化は非常に重要です。リストのアイテム数が多い場合、最適化の有無でパフォーマンスに大きな差が出ます。
renderItemのメモ化
FlatListのrenderItemプロップに渡す関数は、useCallbackでメモ化することが重要です。
// ❌ 悪い例: renderItemが毎回新しい関数を作成
const MyList = ({ items }) => {
return (
<FlatList
data={items}
renderItem={({ item }) => <ItemComponent item={item} />}
keyExtractor={item => item.id.toString()}
/>
);
};
// ✅ 良い例: useCallbackでメモ化
const MyList = ({ items }) => {
const renderItem = useCallback(
({ item }: { item: ItemType }) => <ItemComponent item={item} />,
[] // 依存配列を適切に設定
);
const keyExtractor = useCallback(
(item: ItemType) => item.id.toString(),
[]
);
return (
<FlatList
data={items}
renderItem={renderItem}
keyExtractor={keyExtractor}
/>
);
};
Context依存の最適化
リストアイテムがContextを直接参照すると、Context値の変更で全アイテムが再レンダリングされます。これは特に問題になります。
// ❌ 悪い例: リストアイテムが直接Contextを参照
const ListItem: FC<Props> = ({ item }) => {
const { user } = useSession(); // Context変更で全アイテムが再レンダリング
const { setModal } = useModalContext(); // これも同様
const isOwner = user?.id === item.userId;
return (
<View>
<Text>{item.name}</Text>
{isOwner && <Button onPress={() => setModal(true)}>編集</Button>}
</View>
);
};
// ✅ 良い例: 親から必要な値のみを受け取る
interface ListItemProps {
item: ItemType;
isOwner: boolean;
onOpenModal: () => void;
}
const ListItem = memo<ListItemProps>(({ item, isOwner, onOpenModal }) => {
return (
<View>
<Text>{item.name}</Text>
{isOwner && <Button onPress={onOpenModal}>編集</Button>}
</View>
);
});
// 親コンポーネントでContext値を取得
const ParentList = () => {
const { user } = useSession();
const { setModal } = useModalContext();
const handleOpenModal = useCallback(() => {
setModal(true);
}, [setModal]);
const renderItem = useCallback(
({ item }: { item: ItemType }) => (
<ListItem
item={item}
isOwner={user?.id === item.userId}
onOpenModal={handleOpenModal}
/>
),
[user?.id, handleOpenModal]
);
return <FlatList data={items} renderItem={renderItem} />;
};
この最適化の効果:
- Context値が変更されても、親コンポーネントのみが再レンダリングされる
- 各ListItemは、自分に関係するpropsが変更された場合のみ再レンダリングされる
- 例:user.idが変わっても、isOwnerの値が変わらないアイテムは再レンダリングされない
プロパティの最小化
大きなオブジェクトを渡すと、オブジェクト内の無関係なプロパティが変更されただけでも再レンダリングが発生します。
// ❌ 悪い例: オブジェクト全体を渡す
const userData = {
id: '1',
name: 'John',
email: 'john@example.com',
avatar: 'https://...',
settings: { ... },
notifications: [...],
// ... 多数のプロパティ
};
<ItemComponent userData={userData} />
// ✅ 良い例: 必要な値のみを渡す
<ItemComponent
userName={userData.name}
userAvatar={userData.avatar}
/>
getItemLayoutの実装
アイテムの高さが固定の場合、getItemLayoutを実装することで大幅なパフォーマンス向上が見込めます。
const ITEM_HEIGHT = 80;
<FlatList
data={items}
getItemLayout={(data, index) => ({
length: ITEM_HEIGHT,
offset: ITEM_HEIGHT * index,
index,
})}
renderItem={renderItem}
/>
getItemLayoutを実装すると、FlatListはスクロール時にアイテムの位置を計算する必要がなくなります。これにより、長いリストでも高速にスクロールできます。
FlashListの検討
標準のFlatListよりも高速なFlashListへの置き換えも選択肢の一つです。
yarn add @shopify/flash-list
import { FlashList } from '@shopify/flash-list';
<FlashList
data={items}
renderItem={renderItem}
estimatedItemSize={80} // 推定アイテム高さを指定
/>
FlashListは、FlatListと比較して以下の利点があります。
- より効率的なセル再利用
- メモリ使用量の削減
- スムーズなスクロール
6. React Hooks依存配列の最適化
ESLintのreact-hooks/exhaustive-depsルールをerrorに設定し、依存配列の問題を自動的に検出できるようにしました。
ESLint設定の追加
// eslint.config.js
const reactHooks = require('eslint-plugin-react-hooks');
module.exports = [
{
plugins: {
'react-hooks': reactHooks,
},
rules: {
'react-hooks/exhaustive-deps': 'error',
},
},
];
実際に修正した例
依存配列の問題は、一見正しく見えても実は問題があるケースが多いです。
// Before: routerは安定した参照なので依存配列に含める必要がない
useEffect(() => {
if (data?.hygienist?.bankAccountConfirmationStatus === 'awaiting') {
router.replace('/examinations/bank-account');
}
}, [data, router, isSubmitting]); // routerは不要
// After: 不要な依存を削除
useEffect(() => {
if (data?.hygienist?.bankAccountConfirmationStatus === 'awaiting') {
router.replace('/examinations/bank-account');
}
}, [data, isSubmitting]);
なぜrouterを削除したか:
Expo Routerのrouterオブジェクトは、アプリのライフサイクル全体で同じ参照を維持します。そのため、依存配列に含める必要はありません。不要な依存を含めると、実際には何も変わっていないのにeffectが再実行される可能性があります。
よくある依存配列の問題
| パターン | 問題 | 解決策 |
|---|---|---|
| 安定した参照を含める | 不要な再実行 | 削除する |
| 依存を省略する | 古い値を参照する(stale closure) | ESLintの警告に従う |
| オブジェクトや配列を含める | 毎回新しい参照で再実行 | useMemoでメモ化 |
| 関数を含める | 毎回新しい参照で再実行 | useCallbackでメモ化 |
7. その他の最適化
lodashのインポート最適化
lodashを全体インポートすると、使っていない関数もバンドルに含まれてしまいます。
// ❌ Before: 全体インポート(バンドルサイズ増大)
import _ from 'lodash';
_.isEqual(a, b);
_.groupBy(items, 'category');
// ✅ After: 個別インポート(Tree Shakingが効く)
import isEqual from 'lodash/isEqual';
import groupBy from 'lodash/groupBy';
isEqual(a, b);
groupBy(items, 'category');
バンドルサイズへの影響:
- 全体インポート: lodash全体(約70KB gzipped)がバンドルに含まれる
- 個別インポート: 使用する関数のみ(数KB)がバンドルに含まれる
console.logのビルド時削除
本番環境でのconsole.logはパフォーマンスに悪影響を与えます。特に、頻繁に呼び出されるコンポーネント内のconsole.logは、レンダリング時間を増加させます。
// babel.config.js
module.exports = function(api) {
const isNotDevelopment =
process.env.APP_ENV === 'staging' ||
process.env.APP_ENV === 'production';
api.cache(true);
return {
presets: ['babel-preset-expo'],
plugins: [
// staging/productionではconsole.logを削除(error, warnは保持)
isNotDevelopment && [
'transform-remove-console',
{ exclude: ['error', 'warn'] }
],
].filter(Boolean),
};
};
なぜerrorとwarnは残すか:
-
console.error: 本番環境でのエラー追跡に有用 -
console.warn: 非推奨機能の使用など、重要な警告を確認するため -
console.log: デバッグ用のログは本番では不要
React Native公式ドキュメントからの知見
React Native Performanceのドキュメントから得た知見も、今回の改善に活かしました。
主要な推奨事項
| カテゴリ | 推奨事項 | 詳細 |
|---|---|---|
| 計測 | リリースビルドでテスト | 開発モードは遅い |
| ログ | console.logを本番から削除 | babel-plugin-transform-remove-console |
| リスト | getItemLayout実装 | スクロールパフォーマンス向上 |
| リスト | FlashList検討 | FlatListより高速 |
| アニメーション | useNativeDriver: true | JSスレッドを回避 |
| 重い処理 | InteractionManager | アニメーション後に実行 |
| 画像アニメーション | transformを使用 | width/heightは避ける |
アニメーションの最適化
// ✅ useNativeDriverでJSスレッドを回避
Animated.timing(animatedValue, {
toValue: 1,
duration: 300,
useNativeDriver: true, // ネイティブスレッドで実行
}).start();
useNativeDriver: trueを指定すると、アニメーションがネイティブスレッドで実行されます。これにより、JSスレッドが重い処理を行っていても、アニメーションがスムーズに動作します。
ただし、以下の制限があります。
-
transformとopacityのみサポート -
width、height、backgroundColorなどは非サポート
重い処理の遅延実行
画面遷移のアニメーション中に重い処理を実行すると、アニメーションがカクつきます。InteractionManagerを使うことで、アニメーション完了後に処理を実行できます。
import { InteractionManager } from 'react-native';
const MyScreen = () => {
useEffect(() => {
// 画面遷移アニメーション完了後に実行
const task = InteractionManager.runAfterInteractions(() => {
// 重いデータ取得処理
fetchLargeData();
});
return () => task.cancel();
}, []);
};
まとめ
実施した改善の全体像
| 施策 | PR数 | 効果 |
|---|---|---|
| NativeBase → 自前コンポーネント | 約40 | 根本的なパフォーマンス改善 |
| BottomSheetModal移行 | 1 | モーダルのスムーズな動作 |
| react-native-toast-message移行 | 1 | NativeBase完全削除 |
| コンポーネントのメモ化 | 複数 | 不要な再レンダリング防止 |
| FlatListの最適化 | 複数 | リスト表示の高速化 |
| Hooks依存配列最適化 | 1 | 不要な再実行防止 |
| lodash個別インポート | 1 | バンドルサイズ削減 |
| console.log削除 | 1 | 本番環境の軽量化 |
改善の効果
NativeBaseからの脱却により、以下の効果が得られました。
- タブ間移動の高速化:5秒以上かかっていた画面遷移が、体感で1秒未満に改善
- バンドルサイズの削減:yarn.lockが1000行以上削減
- 依存関係のシンプル化:パッケージ数が減少し、セキュリティリスクも低減
- コードの見通しの改善:自前コンポーネントにより、動作が予測しやすくなった
学んだこと
今回の改善プロジェクトを通じて、以下のことを学びました。
-
UIライブラリの選定は慎重に:便利さとパフォーマンスはトレードオフの関係にあると実感しました。開発初期は便利でも、アプリの規模が大きくなるとパフォーマンスの問題が顕在化することがあります。
-
計測が重要:React DevTools Profilerで原因を特定してから対策を打つことで、効果的な改善ができました。「なんとなく遅い」という感覚ではなく、データに基づいた意思決定が大切だと改めて感じました。
-
段階的な移行が安全:45個のPRに分けて移行することで、問題が発生した場合も影響範囲を限定できました。大規模なリファクタリングでも、小さなステップに分割すれば怖くないと分かりました。
-
シンプルな実装が速い:自前コンポーネントはオーバーヘッドを最小化し、パフォーマンスを向上させます。「必要な機能だけを実装する」というシンプルさが、結果的にメンテナンス性の向上にもつながりました。
-
メモ化はセットで:
React.memoとuseCallbackはセットで使わないと効果が薄いことを身をもって体験しました。片方だけでは不十分だったケースが何度もありました。 -
呼び出し側でのメモ化を徹底:カスタム比較関数に頼るよりも、
StyleSheet.createで定義したstyleやuseCallbackでメモ化した関数を渡すことを徹底する方が、シンプルで保守しやすいコードになると気づきました。
パフォーマンス改善は一度やって終わりではなく、継続的に計測・改善していくことが重要だと感じています。今後もReact DevTools Profilerを活用して、定期的にパフォーマンスをチェックしていく予定です。
参考リンク
- React Native Performance - 公式パフォーマンスガイド
- @gorhom/bottom-sheet - BottomSheetライブラリ
- react-native-toast-message - Toastライブラリ
- FlashList - 高速リストコンポーネント
- babel-plugin-transform-remove-console - console.log削除プラグイン
Discussion