Wednesday, May 27, 2020

React Native Part 2: State with Hooks



React Native is based on Components, which are reusable piece of functionalities.

React Native comes with Class based components and Functional components. Functional component is preferred of creating components.

React Hooks are JavaScript functions which can be used from inside functional components. React Hooks was introduced with React version 16.8.
 React Hooks can be used to manage state in a functional component and for handling side effects like Http calls.

For using state management with Hooks we have to import useState from react.

useState() function can be used to initialize the  state. It uses two elements first to hold the value of the state and second the method to update the state.



import React, {useState} from 'react';
import { StyleSheet, Text, View } from 'react-native';

export default function App() {
  const [name, setName] = useState('Shalvin');
  return (
    <View style={styles.container}>
      <Text>Hello { name}</Text>
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#fff',
    alignItems: 'center',
    justifyContent: 'center',
  },
});





Set State 

import React, {useState} from 'react';
import { StyleSheet, Text, View, Button } from 'react-native';

export default function App() {
  const [name, setName] = useState('Shalvin');
  return (
    <View style={styles.container}>
      <Text>Hello { name}</Text>
      
      <Button title = "Set Name" 
      onPress = { () => setName('Shalvin P D')}/>
    </View>
  );
}



Object State
import React, {useState} from 'react';
import { StyleSheet, Text, View, Button } from 'react-native';

export default function App() {
  const [name, setName] = useState('Shalvin')
  const [contact, setContact] = useState(
    {name: 'Shalvin', location: 'Dubai'});

    const changeContact = () =>
    {
      setContact({name: 'Shalvin P D', location: 'Kochi'});
    }

  return (
    <View style={styles.container}>
      <Text>Hello { name}</Text>

      <Button title = "Set Name" 
      onPress = { () => setName('Shalvin P D')}/>

      <Text>Hello {contact.name} located at {contact.location}</Text>
      <Button title= "Set Contact" onPress={ changeContact }></Button>
    </View>
  );
}

No comments:

Post a Comment