Sub topic 1
What React is and what it is for
Prerequisites
This chapter assumes basic HTML and CSS, JavaScript functions and objects, ES modules, and comfort using a terminal. React is a JavaScript library for building user interfaces. It helps you describe what the screen should show and update that screen when data changes.
Describing UI as a function of state
State is data that can change while an application runs. React uses a declarative model: you describe the result you want, and React updates the browser when state changes.
A useful model is:
UI = function(state)
For example, a counter displays 0 when its state is 0 and 1 after a user clicks its button. You do not manually find the text node and replace it. You update the state, and React renders the correct result.
import { useState } from 'react'
function Counter({ label }) {
const [count, setCount] = useState(0)
return (
<button onClick={() => setCount(count + 1)}>
{label}: {count}
</button>
)
}
export default CounterBuilding UIs from components
A component is a reusable function that returns part of a user interface. Components let you split a large screen into smaller pieces, such as Header, ProductCard, and Counter. Each component can have its own markup, inputs, and state.
Writing markup with JSX
JSX is a JavaScript syntax that looks like HTML. React uses it to describe elements in a component’s returned UI. Use curly braces to insert JavaScript expressions, and use className instead of the HTML class attribute.
Passing data with props
Props are read-only inputs passed from a parent component to a child component. In the example, label="Clicks" passes a string to Counter. The function receives it through its parameter:
<Counter label="Clicks" />Props make one component reusable with different data.
Remembering values with useState
useState is a React hook, which is a function that adds a React feature to a component. It returns the current value and a setter function. Calling the setter schedules a new render with the updated value.
Exercise
What will the button display after two clicks when its initial count is 0?
Show answer
It will display the label followed by 2, such as “Clicks: 2”.