Skip to content

Instantly share code, notes, and snippets.

@MiguelCamilo
Created February 10, 2023 15:38
Show Gist options
  • Save MiguelCamilo/1c00aafa6c0b110bb5878dbe3ab6aa9e to your computer and use it in GitHub Desktop.
Save MiguelCamilo/1c00aafa6c0b110bb5878dbe3ab6aa9e to your computer and use it in GitHub Desktop.
Classes Component in JS vs React || Quick Reference 💻
import { Component } from "react";
// old method of class in react
class CountClass extends Component {
constructor(props) {
super(props);
this.state = {
count: 0,
title: "Welcome",
};
}
componentDidMount() {
// when a component changes it will only change the title
this.setState({ title: "Our New Title" });
}
render() {
const { count, title } = this.state;
return (
<section>
<h2>{title}</h2>
<h3>You clicked {count} times.</h3>
<button onClick={() => this.setState({ count: count + 1 })}>
Click Here
</button>
</section>
);
}
}
export default CountClass
import { useState, useEffect } from "react";
// react functional component class
export default function CountHooks() {
const [count, setCount] = useState(0);
const [title, setTitle] = useState("Welcome");
useEffect(() => {
setTitle("Our New Title");
}, []);
useEffect(() => {
document.title = `${count} clicks`;
}, [count]);
return (
<section>
<h2>{title}</h2>
<h3>You clicked {count} times.</h3>
<button onClick={() => setCount(count + 1)}>Click Here</button>
</section>
);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment