Created
September 16, 2020 13:52
-
-
Save thibaut-d/948234e65c4d80be18548aed24de2023 to your computer and use it in GitHub Desktop.
React Native functional component with internal state management
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import React, { FC, useEffect, useState } from 'react' | |
import { StyleSheet, Text, TouchableOpacity, View } from 'react-native' | |
interface Props { | |
/** prop documentation */ | |
restart?: number | |
} | |
/** | |
* Component description | |
* | |
* @param props - {@link Props} | |
*/ | |
const ComponentName: FC<Props> = ({ restart }: Props) => { | |
const [count, setCount] = useState<number>(0) | |
useEffect(() => { | |
let mounted = true | |
// Declaration | |
const init = async (): Promise<void> => { | |
const restartAt = await getRestartAt(restart) | |
// protect delayed effects that could happen after that the component un-mount | |
if (mounted) setCount(restartAt) | |
} | |
// Execution | |
init() | |
// cleanup | |
return (): void => { | |
mounted = false | |
} | |
}, [restart]) | |
return ( | |
<View style={styles.container}> | |
<TouchableOpacity style={styles.inContainer} onPress={(): void => setCount(count + 1)}> | |
<Text>Add 1</Text> | |
</TouchableOpacity> | |
</View> | |
) | |
} | |
const styles = StyleSheet.create({ | |
container: { | |
flex: 1, // full space | |
flexDirection: 'row', // elements disposition | |
justifyContent: 'center', // following flexDirection | |
alignItems: 'center', // perpendicular to flexDirection | |
}, | |
inContainer: { | |
alignSelf: 'center', // following flex direction | |
}, | |
}) | |
export default ComponentName |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment