DEV Community

Cover image for Stateless components in React Native
Dale L. Jefferson
Dale L. Jefferson

Posted on • Edited on • Originally published at dalejefferson.com

2

Stateless components in React Native

With the arrival of React 0.14 into React Native, we now have a third way of creating components in React Native, stateless components.

Three ways

// Create Class
const Heading = createClass({
  render() {
    return <Text>{this.props.title}</Text>;
  }
});

// ES6 Classes
class Heading extends Component {
  render() {
    return <Text>{this.props.title}</Text>;
  }
}

// Stateless functions
const Heading = ({title}) => <Text>{title}</Text>;

Example

// index.ios.js
import React, {
  AppRegistry,
  StyleSheet,
  View,
  Text
} from "react-native";

const styles = StyleSheet.create({
  page: {
    flex: 1,
    justifyContent: "center",
    alignItems: "center",
    backgroundColor: "rgb(142, 68, 173)"
  },
  heading: {
    fontSize: 36,
    fontWeight: "bold",
    color: "white"
  }
});

const Heading = ({title}) => (
  <Text style={styles.heading}>{title}</Text>
);

const App = () => (
  <View style={styles.page}>
    <Heading title="Stateless" />
  </View>
);

AppRegistry.registerComponent("MyApp", () => App);

I’m using stateless components from the root of the project in this example but obviously, you will need at least one stateful component. A good pattern is to have container components wrapping presentational components using stateless components for the latter.

Stateless components don’t have lifecycle methods or obviously state, but they really reduce the amount of boilerplate code you have to write.

EDIT: Scott Feeney pointed out that stateless components can have propTypes and defaultProps.

const Heading = ({title}) => (
    <Text style={styles.heading}>
        {title}
    </Text>
)

Heading.propTypes = { PropTypes.string }
Heading.defaultProps = { title: 'Stateless' }

Hostinger image

Get n8n VPS hosting 3x cheaper than a cloud solution

Get fast, easy, secure n8n VPS hosting from $4.99/mo at Hostinger. Automate any workflow using a pre-installed n8n application and no-code customization.

Start now

Top comments (0)

Billboard image

Create up to 10 Postgres Databases on Neon's free plan.

If you're starting a new project, Neon has got your databases covered. No credit cards. No trials. No getting in your way.

Try Neon for Free →