kota's memex
class Square extends React.Component {
	constructor(props) {
		super(props)
		this.state = {
			value: null,
		};
	}

	render() {
		return (
			<button className="square" onClick={() => console.log("click")}>
				{this.props.value}
			</button>
		)
	}
}

React components can have state by setting this.state in their constructors. this.state should be considered as private to a React component that it’s defined in.

In JavaScript classes, you need to always call super when defining the constructor of a subclass. All React component classes that have a constructor should start with a super(props) call.

useState

A simpler (and more modern) way to handle state for components:

import { useState } from "react";

const Home = () => {
  const [name, setName] = useState("mario");

  const handleClick = () => {
    setName("luigi");
  };

  return (
    <div className="home">
      <h2>Homepage</h2>
      <p>{name}</p>
      <button onClick={handleClick}>Click Me</button>
    </div>
  );
};

export default Home;

lists

<li key={user.id}>{user.name}: {user.taskCount} tasks left</li>

When a list is re-rendered, React takes each list item’s key and searches the previous list’s items for a matching key. If the current list has a key that didn’t exist before, React creates a component. If the current list is missing a key that existed in the previous list, React destroys the previous component. If two keys match, the corresponding component is moved. Keys tell React about the identity of each component which allows React to maintain state between re-renders.

key is a special and reserved property in React (along with ref, a more advanced feature). When an element is created, React extracts the key property and stores the key directly on the returned element. Even though key may look like it belongs in props, key cannot be referenced using this.props.key. React automatically uses key to decide which components to update. A component cannot inquire about its key.

If no key is specified, React will present a warning and use the array index as a key by default. Using the array index as a key is problematic when trying to re-order a list’s items or inserting/removing list items. Explicitly passing key={i} silences the warning but has the same problems as array indices and is not recommended in most cases.

Keys do not need to be globally unique; they only need to be unique between component and their siblings.