techStackGuru

React Native Design Patterns


As a popular framework for developing cross-platform mobile applications, React Native incorporates various design patterns that improve code structure, maintainability, scalability, and overall development experience. These are some of the most common design patterns used in React Native.


Component-based Architecture

The UI of React Native is composed of reusable components, based on a component-based architecture.

import React from 'react';
import { View, Text } from 'react-native';

const MyComponent = () => {
  return (
    <View>
      <Text>Hello, World!</Text>
    </View>
  );
};

export default MyComponent;

Container-Component Pattern

Provides a separation between data fetching/state management and UI rendering.

import React, { useState, useEffect } from 'react';
import { View, Text } from 'react-native';

const MyContainerComponent = () => {
  const [data, setData] = useState(null);

  useEffect(() => {
    fetchData();
  }, []);

  const fetchData = async () => {
    // Fetch data from API
    const response = await fetch('https://api.example.com/data');
    const jsonData = await response.json();
    setData(jsonData);
  };

  return (
    <View>
      <Text>{data ? data.title : 'Loading...'}</Text>
    </View>
  );
};

export default MyContainerComponent;

Higher-Order Components (HOC):

This pattern involves a function taking a component and returning a new component that has more functionality.

import React from 'react';
import { TouchableOpacity } from 'react-native';

const withBackgroundColor = (WrappedComponent, color) => {
  return (props) => (
    <TouchableOpacity style={{ backgroundColor: color }}>
      <WrappedComponent {...props} />
    </TouchableOpacity>
  );
};

const MyButton = ({ onPress }) => (
  <TouchableOpacity onPress={onPress}>
    <Text>Click me</Text>
  </TouchableOpacity>
);

export default withBackgroundColor(MyButton, 'blue');

Render Props:

In this pattern, the logic of a component is encapsulated into a function prop.

import React from 'react';
import { View, Text } from 'react-native';

const RenderPropsComponent = ({ render }) => {
  return (
    <View>
      {render && render()}
    </View>
  );
};

const App = () => (
  <RenderPropsComponent
    render={() => (
      <Text>Hello, Render Props!</Text>
    )}
  />
);

export default App;

Flux/Redux:

This pattern helps manage application state by creating predictable state containers.

import React from 'react';
import { View, Text } from 'react-native';

const RenderPropsComponent = ({ render }) => {
  return (
    <View>
      {render && render()}
    </View>
  );
};

const App = () => (
  <RenderPropsComponent
    render={() => (
      <Text>Hello, Render Props!</Text>
    )}
  />
);

export default App;