Created
February 9, 2019 14:19
-
-
Save hckhanh/d20e5758e50bd0522a662b664f3f416d to your computer and use it in GitHub Desktop.
Handle componentWillUnmount() logic for DataSource
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import React, { useEffect, useState } from "react"; | |
import DataSource from "../DataSource"; | |
const TextBlock = ({ text }) => <>{text}</>; | |
export function BlogPost({ id }) { | |
// State is declared in pair: state value and setState function | |
const [data, setData] = useState(DataSource.getBlogPost(id)); | |
// Similar to componentDidMount and componentDidUpdate: | |
useEffect(() => { | |
const setDataSourceData = () => setData(DataSource.getBlogPost(id)); | |
DataSource.addChangeListener(setDataSourceData); | |
// Similar to componentWillUnmount | |
return () => DataSource.removeChangeListener(setDataSourceData); | |
}); | |
return <TextBlock text={data} />; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment