React Native Hooks & How To Use useState and useEffect

What is React Hook?

Why React Hook?

How To Use use Hooks with useState and useEffect ?

Example Using Classes

class FriendStatusWithCounter extends React.Component {
constructor(props) {
super(props);
this.state = { count: 0, isOnline: null };
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';
}
}

Example Using Hooks

import React, { useState, useEffect } from 'react';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';
}
componentDidUpdate(prevProps, prevState) {
if (prevState.count !== this.state.count) {
document.title = `You clicked ${this.state.count} times`;
}
}
useEffect(() => {
document.title = `You clicked ${count} times`;
}, [count]); // Only re-run the effect if count changes

Rules of Hooks

Things to Keep in mind

References