Using React’s useEffect like a pro

A brief history

componentDidUpdate(prevProps, prevState) {
if (prevProps.foo !== this.props.foo) {/* do something */}
if (prevState.bar !== this.state.bar) {/* do something else */}
}

Enter React Stateless Components

import React from "react";function MyFunc() {
return <div>Hey!</div>
}

Enter React.useEffect

import React from "react";function MyFunc(props) {  const [bar setBar] = React.useState(null);

React.useEffect(() => {
console.log("componentDidMount");
return () => {
console.log("componentDidUnmount");
}
}, []);

React.useEffect(() => {
console.log("componentDidUpdate when 'bar' changes");
}, [bar]);
React.useEffect(() => {
console.log("componentDidUpdate when 'props.foo' changes");
}, [props.foo]);
return <div>Hey!</div>
}

Going beyond lifecycle management

Hello Custom Hooks

function FriendListItem(props) {
const isOnline = useFriendStatus(props.friend.id);
return (
<li style={{ color: isOnline ? 'green' : 'black' }}>
{props.friend.name}
</li>
);
}
import React, { useState, useEffect } from 'react';

function useFriendStatus(friendID) {
const [isOnline, setIsOnline] = useState(null);

function handleStatusChange(status) {
setIsOnline(status.isOnline);
}

useEffect(() => {
ChatAPI.subscribeToFriendStatus(friendID, handleStatusChange);
return () => {
ChatAPI.unsubscribeFromFriendStatus(friendID, handleStatusChange);
};
});

return isOnline;
}

Conclusion

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store