Hooks in React Native

Updated 7 October 2024

Save

In this blog, We are going to learn about React native hooks, Hooks are a new addition to 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 React supports component functions they suggest their developers use component functions rather than component 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 this 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 the 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 buttons: the first is the ‘Add Count’ button that increases the count by +1, and the second is the ‘Minus’ button that decreases the count by -1.

I also display a text element that shows the current count value.

Here we are done with the useState 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.

hooks-in-react-native-output-minus

Here Is The Output Of The Project:

Conclusion

This guide on React Native hooks highlights the simplicity and efficiency of managing state with useState and handling side effects with useEffect. By understanding these hooks, developers can create more dynamic and responsive functional components.

In this blog, we explored how to implement state management and lifecycle features in React Native.

You can also check other blogs from here.

Thank you for reading! ❤️

We hope this blog helps you enhance your skills in using hooks effectively in your React Native applications.

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