Skip to content

Instantly share code, notes, and snippets.

@thibaut-d
Created September 16, 2020 13:52
Show Gist options
  • Save thibaut-d/948234e65c4d80be18548aed24de2023 to your computer and use it in GitHub Desktop.
Save thibaut-d/948234e65c4d80be18548aed24de2023 to your computer and use it in GitHub Desktop.
React Native functional component with internal state management
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