Skip to content

Instantly share code, notes, and snippets.

@polyrand
Last active January 26, 2020 20:51
Show Gist options
  • Save polyrand/28af98eb51892c6620d795df71133ae2 to your computer and use it in GitHub Desktop.
Save polyrand/28af98eb51892c6620d795df71133ae2 to your computer and use it in GitHub Desktop.
useEffect snippet
import React, { useState, useEffect } from "react";
import ReactDOM from "react-dom";
// import "./App.css";
class ExampleClass extends React.Component {
constructor(props) {
super(props);
this.state = { count: 0 };
}
componentDidMount() {
document.title = `You clicked ${this.state.count} times`;
}
componentDidUpdate() {
document.title = `You clicked ${this.state.count} times`;
}
render() {
return (
<div>
<p>You clicked {this.state.count} times</p>
<button
onClick={() =>
this.setState({
count: this.state.count + 1
})
}
>
Click me!
</button>
</div>
);
}
}
function Example(props) {
const [count, setCount] = useState(0);
useEffect(() => {
document.title = `You clicked ${count} times`;
});
return (
<div>
<p>You clicked {count} times</p>
<button onClick={() => setCount(count + 1)}>Click me!</button>
</div>
);
}
function App() {
return (
<div>
<h1>test!</h1>
<ExampleClass />
<Example />
</div>
);
}
ReactDOM.render(<App />, document.getElementById("root"));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment