Skip to content

Instantly share code, notes, and snippets.

@hckhanh
Last active February 9, 2019 14:07
Show Gist options
  • Save hckhanh/c1728e3efb5f56c53d9be9f03e4cff2c to your computer and use it in GitHub Desktop.
Save hckhanh/c1728e3efb5f56c53d9be9f03e4cff2c to your computer and use it in GitHub Desktop.
Use useEffect to handle componentDidMount
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