I have been watching a few tutorials recently on RN and I have noticed a few of them do not use class when creating a component, instead, they are using const. The code below shows the homescreen for the app for that particular tutorial. My question is: is there a reason they are doing it this way and not using class? Also, does it matter? Is there a particular reason you would use const instead of class?
const HomeScreen = ({ navigation }) => {
return (
<View>
<Text style={styles.textStyle}>This is the Home Screen</Text>
<Button title="Go to Components Demo"
onPress={() => navigation.navigate('Components')}
/>
<Button title="Go to list demo"
onPress={() => navigation.navigate('List')}
/>
<Button title="Go to Image Screen"
onPress={() => navigation.navigate('Image')}
></Button>
<Button title="Go to Counter"
onPress={() => navigation.navigate('Counter')}
></Button>
<Button title="Colors"
onPress={() => navigation.navigate('Color')}
></Button>
<Button title="Squares"
onPress={() => navigation.navigate('Square')}
></Button>
</View>
);
};
const styles = StyleSheet.create({
textStyle: {
fontSize: 30,
textAlign: "center"
},
});
export default HomeScreen;
if you don't use state, you should use const which is called stateless function. it's about performance. if you use state, you have to use class. (earlier versions of react) if you upgrade react-native and use hooks, it will be different.
i think you should check this article about class vs stateless function.
The example you posted is a stateless function component
. It is simply a JavaScript arrow function
that is being assigned to a variable const HomeScreen =
. You could also write it as a standard anonymous function:
// the props you give to <HomeScreen/> get passed as parameter to the function
// by React. You can destructure them right in place, like with ({navigation}).
const HomeScreen = function({ navigation }) {
...
return (...)
}
Stateless function components don't have state. They can be used, if you don't need state and lifecycle methods, etc. Furthermore they can be turned into stateFUL function components by using hooks.
Hooks are predefined functions that can be used inside a function component to enhance it with state, life cycle management, etc. But that's a broader topic.
Without hooks you can use stateless components instead of class components to keep your code small (function instead of class, no this, no render function, just return, reuse code more easily by importing functions and using it inside the component)
To improve performance you'd need hooks (useMemo() hook, e.g.) again. It takes some time to get used to the concept of hooks, but it's worth it. I prefer them over class components now, mainly because the code is cleaner.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With