Home » React JS

How to use React JS Hooks in React Native?

In this article, we will briefly see how to use React JS Hooks in React Native code?
Submitted by Godwill Tetah, on February 09, 2020

In my articles, I'm going to be using either expo or snack online IDE and android emulator.

React Hooks is simply an awesome tool that helps us use states and other react features without writing a class component. That is, it allows you to operate react js states inside function components.

The Hook we are using in this tutorial is called the useState Hook because there is also the effect hook.

The useState hook takes an argument which is the initial state of the state you are building.

The developers of this say; It returns the current state value and a function that allows you to update it when it is called in an event handler.

Here are sample and output.

Open your App's App.js file and type the following

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

export default function App () {

  const [Msg,setMsg]= useState('Includehelp');

  return (
    <View style={styles.container}>

      <Text> Hello {Msg} </Text>
    <Button 
    title='click'
    onPress={()=>setMsg('my name is Godwill')} 
    />
    </View>
  );
}
const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#fff',
    alignItems: 'center',
    justifyContent: 'center',
  },
});

Output

How to use React JS Hooks in React Native?

From the code above, you can see the format of creating a new react js hook. The hook is immediately before the return statement.

The brackets after the const keyword contain the state called Msg and the setMsg which allows us the reset the Msg state anytime from the code.

Take note of importing useState from 'react' and not react-native.

The state is then reset after the button Press which changes the statement in our output.

So that's the format and brief explanation on hooks.

Thanks for coding with me! See you @ the next article. Feel free to drop a comment or question. God Bless You!



Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.