React-native hooks example

How to setState in react-native function

Hi Guys, In this article, we are going to learn about React-native hooks example, After React 16.8 we can use hooks in our project, React hooks meanly use for state management in function. Normally in class, we use setState() to refresh data on screen but if we are using function then setState didn’t work in function, to refresh data in the function we need to use Hooks so let’s start with an example.

React-native hooks example
React-native hooks example

1. Create a new project

2. Imports following components

3. Create a function instead of class

Nowadays if you create a new project react-native show function by default like below, you can delete default function and write our own class, it’s just a new way of coding nothing else. but need to use hooks in function to set data in state and reflect that change data on the screen.

As we see in about function we use useState which is imported from React

in the above code, outPutText display String value from useState i.e. This is hooks example, and setOutPutText use to set the new value to State and refresh the screen with the new value.

4. Check this full code App.js

As we see in the above source code, I added anonymous arrow function on Button onPress and setOutPutText new Text this update state value and automatically refresh the screen as you see below

5. Output:

React-native hooks example
React-native hooks example

Thank you 🙂

Leave a Reply

Your email address will not be published. Required fields are marked *