Hooks In React Native

November 08, 2021 Publish By : EXPERT APP DEVS 4 min read Viewed By : 222
hooks in react native

Hooks Introduction -

Hooks are introduced in React 16.8 are a new addition, by using hooks you avail to use the state and other react features without writing any class.

hooks

It is basically used for handling state and react side effects in functional components.  By using hooks you can use the stateful functions inside the functional component.

You are not able to use the hooks within any class component. React Native provides some built-in hooks like - useState and useEffect.
Following are some important points about hooks.

About Hooks - 

  • Hooks are best practice
  • Hooks are easy to understand
  • Hooks are easy to test 
  • Hooks increases the performance of the app

Why Using Hooks - 

If you want to use a functional component then you need to write a functional method and within the functional component if you want to use state or lifecycle then we use the hooks. Also, you can use this in existing functional components.

How To Use Hooks with useState and useEffect  -

Here we are going to see the example of how we use the useEffect and useState with react native.

Example Using Class -

class FriendStatusWithCounter extends React.Component {

 constructor(props) {

   super(props);

   this.handleStatusChange = this.handleStatusChange.bind(this);

 }

 componentDidMount() {

   document.title = `You clicked ${this.state.count} times`;

   ChatAPI.subscribeToFriendStatus(

     this.props.friend.id,

     this.handleStatusChange

   );

 }

 componentDidUpdate() {

   document.title = `You clicked ${this.state.count} times`;

 }

 componentWillUnmount() {

   ChatAPI.unsubscribeFromFriendStatus(

     this.props.friend.id,

     this.handleStatusChange

   );

 }

 handleStatusChange(status) {

   this.setState({

     isOnline: status.isOnline

   });

 }

render() {

   if (this.state.isOnline === null) {

     return 'Loading...';

   }

   return this.state.isOnline ? 'Online' : 'Offline';

 }

}

useEffect Hook is basically a combination of componentDidMount, componentDidUpdate, and componentWillUnmount.

useEffect runs every time after the first time and after update every time.

How We Use Hooks State - 

Here we set the state by using useState.

const [count, setCount] = useState(0)

Here you pass the first param which needs to update and the second one is a function which updates the state.

useState(0):  Initialize the as 0

Import here

function FriendStatusWithCounter(props) {

const [count, setCount] = useState(0);

useEffect(() => {

    document.title = `You clicked ${count} times`;

 });

 const [isOnline, setIsOnline] = useState(null);

useEffect(() => {    

   function handleStatusChange(status) {

     setIsOnline(status.isOnline);

   }

   ChatAPI.subscribeToFriendStatus(props.friend.id,

 handleStatusChange);

return () => {

     ChatAPI.unsubscribeFromFriendStatus(props.friend.id,             handleStatusChange);

   };

 });

if (isOnline === null) {

   return 'Loading...';

 }

 return isOnline ? 'Online' : 'Offline';

}

How We Use componentDidUpdate With Hooks - 

It is not possible to clean up or apply the effect after every render might create some performance problems. You can handle this by adding some extra comparison in the class component with prevProps or prevState inside componentDidUpdate.

componentDidUpdate(prevProps, prevState) {

   if (prevState.count !== this.state.count) {

     document.title = `You clicked ${this.state.count} times`;

   }

 }

How We Use useEffect With Hooks -

If any value is not changed you can skip it by using useEffect, here is the example.

useEffect(() => {

   document.title = `You clicked ${count} times`;

 }, [count]); // Re-run the effect

Some Hooks Rules - 

Following are some rules which need to follow when you use the hooks in your project.

  • Hooks only called at the top level of the app
  • Never call hooks within any condition, nested functions, loops, etc.
  • So always use the hooks at the top level of your functions.
  • Hooks are always called in the same order and each time within component render.
  • Hooks are always called by react functions.
  • Never call hooks by using regular javascript functions.

effect hook

How We Clear Data At Unmounting -

Here we see how we clear the interval when we leave the component.

clear data at unmounting

How We Use The Lifecycle Method in Hooks - 

Following are the cases where we use the lifecycle method and there are some stages of the lifecycle method.

1. Initial Render

getDerivedStateFromProps

    useEffect( ()=>{},[propp1, prop2])

componentDidMount

useEffect( ()=> {},[])

 

2. Updates

getDerivedStateFromProps

    useEffect( ()=>{},[propp1, prop2])

shouldComponentUpdate()

useMemo()

componentdidUpdate()

useEffect( ()=>{})

getSnapshotBeforeUpdate

custom Hook to hold previous state

 

3. Unmount

useEffect( ()=>{return()=>{//cleanup}},[])

So that’s it, i think you like the blog if you have any query then please ask.

Happy Coding

 

Need a consultation?

Drop us a line! We are here to answer your questions 24/7.