In React, a component is a piece of reusable code that represents a part of a user interface. Components are used to render, manage, and update the UI elements in your application.
<button>
is a JSX element. A JSX element is a combination of JavaScript code and HTML tags that describes what you’d like to display.// <button> is a JSX element. // A JSX element is a combination of JavaScript code and HTML // tags that describes what you’d like to display. export default function Square() { return <button className="square">X</button>; }
function Square({ value })
indicates the Square component can be passed a prop called value
.// function Square({ value }) indicates the Square component // can be passed a prop called value. function Square({ value }) { return <button className="square">value</button>; }
React provides a special function called
useState
that you can call from your component to let it “remember” things. Let’s store the current value of the Square
in state, and change it when the Square
is clicked.value
stores the value and setValue
is a function that can be used to change the value. The null
passed to useState
is used as the initial value for this state variable, so value
here starts off equal to null
.const Square = () => { const [value, setValue] = useState(null); const handleClick = () => { console.log("Clicked!"); }; return ( <button className="square" onClick={handleClick}> {value} </button> ); };
In React, it’s conventional to use
onSomething
names for props which represent events and handleSomething
for the function definitions which handle those events.Why immutability is important
Warning: Each child in a list should have a unique "key" prop.
It’s strongly recommended that you assign proper keys whenever you build dynamic lists. If you don’t have an appropriate key, you may want to consider restructuring your data so that you do.
key
is a special and reserved property in React. 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 is passed as props, React automatically uses key
to decide which components to update. There’s no way for a component to ask what key
its parent specified.If no key is specified, React will report an error 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 error 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 components and their siblings.
More React Article
Memo
Hydration
Reference
Â