Last active
February 9, 2019 14:07
-
-
Save hckhanh/c1728e3efb5f56c53d9be9f03e4cff2c to your computer and use it in GitHub Desktop.
Use useEffect to handle componentDidMount
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(() => { | |
| DataSource.addChangeListener(() => setData(DataSource.getBlogPost(id))); | |
| }); | |
| return <TextBlock text={data} />; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment