React Native Hooks & How To Use useState and useEffect

Gilshaan Jabbar
5 min readApr 3, 2020

What is React Hook?

Hooks are a new addition in React 16.8. They let you use state and other React features without writing a class. It mainly uses to handle the state and side effects in react functional component. React Hooks are a way to use stateful functions inside a functional component. Hooks don’t work inside classes — they let you use React without classes React provides a few built-in Hooks like useState and useEffect.

. It Enforces best practices
. Easy to under understand
. Easy to test
. It increases the performance and so on.

Why React Hook?

If you write a function component, and then you want to add some state to it, previously you do this by converting it to a class. But, now you can do it by using a Hook inside the existing function component.

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

You can think of useEffect Hook as componentDidMount, componentDidUpdate, and componentWillUnmount combined.

By default, useEffect runs both after the first render and after every update.

We can return a function(could be an arrow function) from our effect for adding and removing subscriptions.

Here we can set the states by -const [count, setCount] = useState(0);

const [count, setCount] : the current state and a function that updates it.

useState(0): Here we initialize the count as 0

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) in Hooks

In some cases, cleaning up or applying the effect after every render might create a performance problem. In class components, we can solve this by writing an extra comparison with prevProps or prevState inside componentDidUpdate:

componentDidUpdate(prevProps, prevState) {
if (prevState.count !== this.state.count) {
document.title = `You clicked ${this.state.count} times`;
}
}

This requirement is common enough that it is built into the useEffect Hook API. You can tell React to skip applying an effect if certain values haven’t changed between re-renders. To do so, pass an array as an optional second argument to useEffect:

useEffect(() => {
document.title = `You clicked ${count} times`;
}, [count]); // Only re-run the effect if count changes

Rules of Hooks

  • Only Call Hooks at the Top Level
  • Don’t call Hooks inside loops, conditions, or nested functions. Instead, always use Hooks at the top level of your React function. By following this rule, you ensure that Hooks are called in the same order each time a component renders. That’s what allows React to correctly preserve the state of Hooks between multiple useState and useEffect calls. (If you’re curious, we’ll explain this in depth below.)
  • Only Call Hooks from React Functions
  • Don’t call Hooks from regular JavaScript functions. Instead, you can:
  • Call Hooks from React function components.
  • Call Hooks from custom Hooks (we’ll learn about them on the next page).

By following this rule, you ensure that all stateful logic in a component is clearly visible from its source code.

Things to Keep in mind

I need to clear the interval when component unmount. So how I do this with effect hook. Without react hook, do you remember, we just clear the interval in another life-cycle method called componentWillUnmount? But in react hook, we can simply do it inside the useEffect.
Inside the return, clear the interval. So interval will be cleared when the component unmounted.

But Now each time when any of state is updated, this hook method is calling.
but we need to call this only at component will mount and unmount. So how can we fix it?
Simply, you can pass the empty array as a second argument. By doing this, this useEffect will call only at the component mount and unmount.

Now, what if I want to call this side effect only when for some state is changed? Let assume, If I have another state called isStarted and initial value of it is false.

If I want to trigger this useEffect when only isStarted state variable is true, then we can pass the isStarted state instead of passing empty array.

References

--

--