DEV Community πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’»

DEV Community πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’» is a community of 963,673 amazing developers

We're a place where coders share, stay up-to-date and grow their careers.

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

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

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' }

Top comments (0)

Visualizing Promises and Async/Await 🀯

async await

☝️ Check out this all-time classic DEV post