Skip to content

Instantly share code, notes, and snippets.

@ajaykumar97
Last active November 4, 2019 13:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ajaykumar97/25c546ba227a22896698741d38fa0c17 to your computer and use it in GitHub Desktop.
Save ajaykumar97/25c546ba227a22896698741d38fa0c17 to your computer and use it in GitHub Desktop.
React-Hooks example
import React, { useState, useEffect } from 'react';
import { View, StyleSheet, Button, Text } from 'react-native';
// eslint-disable-next-line import/no-extraneous-dependencies
import uuidv4 from 'uuid/v4';
const ReactHooks = () => {
const [count, setCount] = useState(0);
const [users, setUsers] = useState([]);
/*
componentDidMount, componentDidUpdate, componentWillUnMount combined
*/
useEffect(() => {
//componentDidMount(after component mount) and componentDidUpdate(after every update)
console.log('Count is: ', count);
return(() => { //componentWillUnMount
console.log('Unmounting the component')
});
)};
useEffect(() => {
//componentdidMount Effect
console.log('componentDidMount effect\n\n');
}, []); //send empty list to call only once
useEffect(() => {
//componentDidUpdate Effect
console.log('componentDidUpdate effect');
}, [count]);
//componentWillUnMount Effect
useEffect(() => () => ( //passing function to be called before unmount
console.log('\n\ncomponentWillUnmount effect')
), []); //send empty list to call only once
const usersList = users.map((user) => (
<View key={user.id}>
<Text>{user.name}</Text>
</View>
));
const getRandomName = (length) => {
let randomString = '';
const characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
const charactersLength = characters.length;
for (let i = 0; i < length; i++) {
randomString += characters.charAt(Math.floor(Math.random() * charactersLength));
}
return randomString;
};
const decreaseCount = () => setCount(count - 1);
const increaseCount = () => setCount(count + 1);
const addNewUser = () => setUsers([...users, { id: uuidv4(), name: getRandomName(5) }]);
return (
<View style={styles.container}>
<View style={styles.buttonContainer}>
<Button
title={'Decrease count'}
onPress={decreaseCount}
/>
<View style={styles.separator} />
<Button
title={'Increase count'}
onPress={increaseCount}
/>
</View>
<Text style={styles.countText}>
Count is: {count}
</Text>
<Button
title={'Add User'}
onPress={addNewUser}
/>
<View style={styles.separator} />
{usersList}
</View>
);
};
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: 'orange',
paddingTop: 20
},
buttonContainer: {
flexDirection: 'row',
alignItems: 'center',
justifyContent: 'center'
},
countText: {
textAlign: 'center',
color: 'white',
marginVertical: 10
},
separator: {
width: 10,
height: 10
}
});
export default ReactHooks;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment