In React Native, components are the fundamental building blocks of the user interface. They enable developers to break down complex UIs into manageable, reusable pieces. Components can be broadly classified into two types: Functional Components and Class Components.
Functional components are the simpler and more modern way to create components in React Native. They are JavaScript functions that return JSX, which is a syntax extension that looks similar to HTML. With the introduction of hooks in React 16.8, functional components can now manage state and lifecycle events, which were previously only possible in class components.
import React from 'react';
import { View, Text, StyleSheet } from 'react-native';
const HelloWorld = () => {
const name = "World";
return (
<View style={styles.container}>
<Text style={styles.text}>Hello, {name}!</Text>
</View>
);
};
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
},
text: {
fontSize: 20,
},
});
export default HelloWorld;
Simpler Syntax:Defined as a function that returns JSX.
Hooks: Can use hooks like useState and useEffect for state management and side effects.
No this Binding:Avoids issues related to the this keyword in class components.
Class components are more traditional and were the primary way to manage state and lifecycle events before hooks were introduced. They are defined using ES6 classes that extend from React.Component.
import React, { Component } from 'react';
import { View, Text, StyleSheet } from 'react-native';
class HelloWorld extends Component {
constructor(props) {
super(props);
this.state = {
name: "World",
};
}
render() {
return (
<View style={styles.container}>
<Text style={styles.text}>Hello, {this.state.name}!</Text>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
},
text: {
fontSize: 20,
},
});
export default HelloWorld;
State Management: Uses this.state and this.setState for managing state.
Lifecycle Methods:Can directly use lifecycle methods like componentDidMount, componentDidUpdate, and componentWillUnmount.
Complex Syntax: Requires more boilerplate and this binding.