Hooks in React Native

Updated 28 November 2023

Save

Hooks in React Native

In this blog, We are going to learn about the react native hooks, Hooks are a new addition in React 16.8. They let you use state and other React features without writing a class.

useState :

This new function “useState” is the first hook that we are going to learn about.

As we already know that React is supporting component functions they suggest their developers use component functions rather than components classes.

We can not use the state as we use it in-class component. So that’s why we need to use state in component function by using the useState function.

Let’s do some code to understand the useState function.

In thi code as you can see we have imported a function called “useSate” from “react”. We will use that function to create a hook.

In the below lines you can see we define a const in the first parameter we define the name of the state variable “count” and the second parameter is a function name that by using this function we can change or update the state value. After this you can see that we assign useState value to the const variable.

useState function takes a parameter that is the default value for the state.

Now you can use the state directly by calling its name as you can see we show {count} and when you want to update the state just call the setCount function in its parameter set your value.

In my case I use two-button first is add count button that we increase the count +1 and then i show a text that will show us the count value then minus button that is to decrease the count -1.

Here we are done with the useSate method.

useEffect :

In our hooks useEffect function is like componentDidMount, componentDidUpdate and componentWillUnmount.

If you’re familiar with React class lifecycle methods, you can think of useEffect.

Here is my App.js class useEffect is just a function that is react like react life cycle methods.

Here is our final output.

hooks-in-react-native-output-plus
hooks-in-react-native-output-minus

Hope this blog will help you to understand the Hooks for react native.

Reference –> https://reactjs.org/docs/hooks-effect.html,

https://reactjs.org/docs/hooks-state.html

author
. . .

Leave a Comment

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


Be the first to comment.

Start a Project


    Message Sent!

    If you have more details or questions, you can reply to the received confirmation email.

    Back to Home