Some things on the screen update in response to user input. For example, clicking an image gallery switches the active image. In React, data that changes over time is called state. You can add state to any component, and update it as needed. In this chapter, you'll learn how to write components that handle interactions, update their state, and display different output over time.
Some things on the screen update in response to user input. For example, clicking an image gallery switches the active image. In React, data that changes over time is called *state.* You can add state to any component, and update it as needed. In this chapter, you'll learn how to write components that handle interactions, update their state, and display different output over time.
</Intro>
@ -22,7 +22,7 @@ Some things on the screen update in response to user input. For example, clickin
## Responding to events {/*responding-to-events*/}
React lets you add event handlers to your JSX. Event handlers are your own functions that will be triggered in response to user interactions like clicking, hovering, focusing on form inputs, and so on.
React lets you add *event handlers* to your JSX. Event handlers are your own functions that will be triggered in response to user interactions like clicking, hovering, focusing on form inputs, and so on.
Built-in components like `<button>` only support built-in browser events like `onClick`. However, you can also create your own components, and give their event handler props any application-specific names that you like.
@ -74,9 +74,9 @@ Read **[Responding to Events](/learn/responding-to-events)** to learn how to add
## State: a component's memory {/*state-a-components-memory*/}
Components often need to change what's on the screen as a result of an interaction. Typing into the form should update the input field, clicking "next" on an image carousel should change which image is displayed, clicking "buy" puts a product in the shopping cart. Components need to "remember" things: the current input value, the current image, the shopping cart. In React, this kind of component-specific memory is called state.
Components often need to change what's on the screen as a result of an interaction. Typing into the form should update the input field, clicking "next" on an image carousel should change which image is displayed, clicking "buy" puts a product in the shopping cart. Components need to "remember" things: the current input value, the current image, the shopping cart. In React, this kind of component-specific memory is called *state.*
You can add state to a component with a [`useState`](/apis/usestate) Hook. Hooks are special functions that let your components use React features (state is one of those features). The `useState` Hook lets you declare a state variable. It takes the initial state and returns a pair of values: the current state, and a state setter function that lets you update it.
You can add state to a component with a [`useState`](/apis/usestate) Hook. *Hooks* are special functions that let your components use React features (state is one of those features). The `useState` Hook lets you declare a state variable. It takes the initial state and returns a pair of values: the current state, and a state setter function that lets you update it.
```js
const [index, setIndex] = useState(0);
@ -235,7 +235,7 @@ Before your components are displayed on the screen, they must be rendered by Rea
Imagine that your components are cooks in the kitchen, assembling tasty dishes from ingredients. In this scenario, React is the waiter who puts in requests from customers and brings them their orders. This process of requesting and serving UI has three steps:
1. **Triggering** a render (delivering the diner's order to the kitchen)
2. **Rendering** the component (getting the order from the kitchen)
2. **Rendering** the component (preparing the order in the kitchen)
3. **Committing** to the DOM (placing the order on the table)
@ -23,7 +23,7 @@ React is a JavaScript library for rendering user interfaces (UI). UI is built fr
## Your first component {/*your-first-component*/}
React applications are built from isolated pieces of UI called "components". A React component is a JavaScript function that you can sprinkle with markup. Components can be as small as a button, or as large as an entire page. Here is a `Gallery` component rendering three `Profile` components:
React applications are built from isolated pieces of UI called *components*. A React component is a JavaScript function that you can sprinkle with markup. Components can be as small as a button, or as large as an entire page. Here is a `Gallery` component rendering three `Profile` components:
<Sandpack>
@ -464,7 +464,7 @@ Read **[Rendering Lists](/learn/rendering-lists)** to learn how to render a list
## Keeping components pure {/*keeping-components-pure*/}
Some JavaScript functions are “pure.” A pure function:
Some JavaScript functions are *pure.* A pure function:
* **Minds its own business.** It does not change any objects or variables that existed before it was called.
* **Same inputs, same output.** Given the same inputs, a pure function should always return the same result.
@ -43,9 +43,9 @@ The last thing you want to do when sharing your code with another contributor is
You can install the [Prettier extension in VSCode](https://marketplace.visualstudio.com/items?itemName=esbenp.prettier-vscode) by following these steps:
1. Launch VS Code
2. Use Quick Open (press `CTRL/CMD + P`)
2. Use Quick Open (press Ctrl/Cmd+P)
3. Paste in `ext install esbenp.prettier-vscode`
4. Press enter
4. Press Enter
#### Formatting on save {/*formatting-on-save*/}
@ -53,8 +53,8 @@ Ideally, you should format your code on every save. VS Code has settings for thi
1. In VS Code, press `CTRL/CMD + SHIFT + P`.
2. Type "settings"
3. Hit enter
3. Hit Enter
4. In the search bar, type "format on save"
5. Be sure the "format on save" option is ticked!
> Prettier can sometimes conflict with other linters. But there's usually a way to get them to run nicely together. For instance, if you're using Prettier with ESLint, you can use [eslint-prettier](https://github.com/prettier/eslint-plugin-prettier) plugin to run prettier as an ESLint rule.
> If your ESLint preset has formatting rules, they may conflict with Prettier. We recommend to disable all formatting rules in your ESLint preset using [`eslint-config-prettier`](https://github.com/prettier/eslint-config-prettier) so that ESLint is *only* used for catching logical mistakes. If you want to enforce that files are formatted before a pull request is merged, use [`prettier --check`](https://prettier.io/docs/en/cli.html#--check) for your continuous integration.
@ -4,7 +4,7 @@ title: Extracting State Logic into a Reducer
<Intro>
Components with many state updates spread across many event handlers can get overwhelming. For these cases, you can consolidate all the state update logic outside your component in a single function, called a "reducer."
Components with many state updates spread across many event handlers can get overwhelming. For these cases, you can consolidate all the state update logic outside your component in a single function, called a *reducer.*
@ -21,7 +21,7 @@ Welcome to the React documentation! This page will give you an introduction to t
## Creating and nesting components {/*components*/}
React apps are made out of components. A component is a piece of the UI (user interface) that has its own logic and appearance. A component can be as small as a button, or as large as an entire page.
React apps are made out of *components*. A component is a piece of the UI (user interface) that has its own logic and appearance. A component can be as small as a button, or as large as an entire page.
React components are JavaScript functions that return markup:
@ -77,7 +77,7 @@ The `export default` keywords specify the main component in the file. If you're
## Writing markup with JSX {/*writing-markup-with-jsx*/}
The markup syntax you've seen above is called JSX. It is optional, but most React projects use JSX for its convenience. All of the [tools we recommend for local development](/learn/installation) support JSX out of the box.
The markup syntax you've seen above is called *JSX*. It is optional, but most React projects use JSX for its convenience. All of the [tools we recommend for local development](/learn/installation) support JSX out of the box.
JSX is stricter than HTML. You have to close tags like `<br />`. Your component also can't return multiple JSX tags. You have to wrap them into a shared parent, like a `<div>...</div>` or an empty `<>...</>` wrapper:
@ -280,7 +280,7 @@ export default function ShoppingList() {
## Responding to events {/*responding-to-events*/}
You can respond to events by declaring event handler functions inside your components:
You can respond to events by declaring *event handler* functions inside your components:
```js {2-4,7}
function MyButton() {
@ -382,7 +382,7 @@ Notice how each button "remembers" its own `count` state and doesn't affect othe
## Using Hooks {/*using-hooks*/}
Functions starting with `use` are called Hooks. `useState` is a built-in Hook provided by React. You can find other built-in Hooks in the [React API reference](/apis). You can also write your own Hooks by combining the existing ones.
Functions starting with `use` are called *Hooks*. `useState` is a built-in Hook provided by React. You can find other built-in Hooks in the [React API reference](/apis). You can also write your own Hooks by combining the existing ones.
Hooks are more restrictive than regular functions. You can only call Hooks *at the top level* of your components (or other Hooks). If you want to `useState` in a condition or a loop, extract a new component and put it there.
Some JavaScript functions are "pure." Pure functions only perform a calculation and nothing more. By strictly only writing your components as pure functions, you can avoid an entire class of baffling bugs and unpredictable behavior as your codebase grows. To get these benefits, though, there are a few rules you must follow.
Some JavaScript functions are *pure.* Pure functions only perform a calculation and nothing more. By strictly only writing your components as pure functions, you can avoid an entire class of baffling bugs and unpredictable behavior as your codebase grows. To get these benefits, though, there are a few rules you must follow.
@ -4,7 +4,7 @@ title: 'Manipulating the DOM with Refs'
<Intro>
Because React handles updating the [DOM](https://developer.mozilla.org/docs/Web/API/Document_Object_Model/Introduction) to match your render output, your components won't often need to manipulate the DOM. However, sometimes you might need access to the DOM elements managed by React--for example, to focus a node, scroll to it, or measure its size and position. There is no built-in way to do those things in React, so you will need a [ref](/learn/referencing-values-with-refs#refs-and-the-dom) to the DOM node.
React automatically updates the [DOM](https://developer.mozilla.org/docs/Web/API/Document_Object_Model/Introduction) to match your render output, so your components won't often need to manipulate it. However, sometimes you might need access to the DOM elements managed by React--for example, to focus a node, scroll to it, or measure its size and position. There is no built-in way to do those things in React, so you will need a *ref* to the DOM node.
</Intro>
@ -80,11 +80,11 @@ To implement this:
3. In the `handleClick` function, read the input DOM node from `inputRef.current` and call [`focus()`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/focus) on it with `inputRef.current.focus()`.
4. Pass the `handleClick` event handler to `<button>` with `onClick`.
While DOM manipulation is the most common use case for refs, the `useRef` Hook can be used for storing other things outside React, like timer IDs. Similarly to state, refs remain between renders. You can even think of refs as state variables that don't trigger re-renders when you set them! You can learn more about refs in [Referencing Values with Refs](/learn/referencing-values-with-refs).
While DOM manipulation is the most common use case for refs, the `useRef` Hook can be used for storing other things outside React, like timer IDs. Similarly to state, refs remain between renders. Refs are like state variables that don't trigger re-renders when you set them. For an introduction to refs, see [Referencing Values with Refs](/learn/referencing-values-with-refs).
### Example: Scrolling to an element {/*example-scrolling-to-an-element*/}
You can have more than a single ref in a component. In this example, there is a carousel of three images and three buttons to center them in the view port by calling the browser [`scrollIntoView()`](https://developer.mozilla.org/en-US/docs/Web/API/Element/scrollIntoView) method the corresponding DOM node:
You can have more than a single ref in a component. In this example, there is a carousel of three images. Each button centers an image by calling the browser [`scrollIntoView()`](https://developer.mozilla.org/en-US/docs/Web/API/Element/scrollIntoView) method the corresponding DOM node:
@ -4,7 +4,7 @@ title: Passing Data Deeply with Context
<Intro>
Usually, you will pass information from a parent component to a child component via props. But passing props can become verbose and inconvenient if you have to pass them through many components in the middle, or if many components in your app need the same information. Context lets the parent component make some information available to any component in the tree below it—no matter how deep—without passing it explicitly through props.
Usually, you will pass information from a parent component to a child component via props. But passing props can become verbose and inconvenient if you have to pass them through many components in the middle, or if many components in your app need the same information. *Context* lets the parent component make some information available to any component in the tree below it—no matter how deep—without passing it explicitly through props.
@ -4,7 +4,7 @@ title: Passing Props to a Component
<Intro>
React components use **props** to communicate with each other. Every parent component can pass some information to its child components by giving them props. Props might remind you of HTML attributes, but you can pass any JavaScript value through them, including objects, arrays, and functions.
React components use *props* to communicate with each other. Every parent component can pass some information to its child components by giving them props. Props might remind you of HTML attributes, but you can pass any JavaScript value through them, including objects, arrays, and functions.
@ -108,7 +108,7 @@ Here's how these look as a tree:
<Diagramname="preserving_state_tree"height={248}width={395}alt="Diagram of a tree of React components. The root node is labeled 'div' and has two children. Each of the children are labeled 'Counter' and both contain a state bubble labeled 'count' with value 0.">
React Tree
React tree
</Diagram>
@ -383,7 +383,7 @@ When you tick or clear the checkbox, the counter state does not get reset. Wheth
<Diagramname="preserving_state_same_component"height={461}width={600}alt="Diagram with two sections separated by an arrow transitioning between them. Each section contains a layout of components with a parent labeled 'App' containing a state bubble labeled isFancy. This component has one child labeled 'div', which leads to a prop bubble containing isFancy (highlighted in purple) passed down to the only child. The last child is labeled 'Counter' and contains a state bubble with label 'count' and value 3 in both diagrams. In the left section of the diagram, nothing is highlighted and the isFancy parent state value is false. In the right section of the diagram, the isFancy parent state value has changed to true and it is highlighted in yellow, and so is the props bubble below, which has also changed its isFancy value to true.">
Since Counter is always in the same position, the count does not reset, event when isFancy state in the parent changes.
Updating the `App` state does not reset the `Counter` state because it stays in the same position
</Diagram>
@ -583,7 +583,7 @@ Here, you switch between _different_ component types at the same position. Initi
<Diagramname="preserving_state_diff_pt1"height={290}width={753}alt="Diagram with three sections, with an arrow transitioning each section in between. The first section contains a React component labeled 'div' with a single child labeled 'Counter' containing a state bubble labeled 'count' with value 3. The middle section has the same 'div' parent, but the child component has now been deleted, indicated by a yellow 'proof' image. The third section has the same 'div' parent again, now with a new child labeled 'p', highlighted in yellow.">
When Counter changes to p, first the Counter is unmounted, then the p is mounted.
When `Counter` changes to `p`, the `Counter` is deleted and the `p` is added
</Diagram>
@ -593,7 +593,7 @@ When Counter changes to p, first the Counter is unmounted, then the p is mounted
<Diagramname="preserving_state_diff_pt2"height={290}width={753}alt="Diagram with three sections, with an arrow transitioning each section in between. The first section contains a React component labeled 'p'. The middle section has the same 'div' parent, but the child component has now been deleted, indicated by a yellow 'proof' image. The third section has the same 'div' parent again, now with a new child labeled 'Counter' containing a state bubble labeled 'count' with value 0, highlighted in yellow.">
When switching back, first the p is unmounted, then the Counter is mounted.
When switching back, the `p` is deleted and the `Counter` is added
</Diagram>
@ -694,7 +694,7 @@ The counter state gets reset when you click the checkbox. Although you render a
<Diagramname="preserving_state_diff_same_pt1"height={362}width={752}alt="Diagram with three sections, with an arrow transitioning each section in between. The first section contains a React component labeled 'div' with a single child labeled 'section', which has a single child labeled 'Counter' containing a state bubble labeled 'count' with value 3. The middle section has the same 'div' parent, but the child components have now been deleted, indicated by a yellow 'proof' image. The third section has the same 'div' parent again, now with a new child labeled 'div', highlighted in yellow, also with a new child labeled 'Counter' containing a state bubble labeled 'count' with value 0, all highlighted in yellow.">
When section changes to div, first the section is unmounted then the new div is mounted.
When `section` changes to `div`, the `section` is deleted and the new `div` is added
</Diagram>
@ -704,7 +704,7 @@ When section changes to div, first the section is unmounted then the new div is
<Diagramname="preserving_state_diff_same_pt2"height={362}width={752}alt="Diagram with three sections, with an arrow transitioning each section in between. The first section contains a React component labeled 'div' with a single child labeled 'div', which has a single child labeled 'Counter' containing a state bubble labeled 'count' with value 0. The middle section has the same 'div' parent, but the child components have now been deleted, indicated by a yellow 'proof' image. The third section has the same 'div' parent again, now with a new child labeled 'section', highlighted in yellow, also with a new child labeled 'Counter' containing a state bubble labeled 'count' with value 0, all highlighted in yellow.">
When switching back, first the div is unmounted then the new section is mounted.
When switching back, the `div` is deleted and the new `section` is added
</Diagram>
@ -917,7 +917,7 @@ h1 {
<Diagramname="preserving_state_diff_position_p1"height={375}width={504}alt="Diagram with a tree of React components. The parent is labeled 'Scoreboard' with a state bubble labeled isPlayerA with value 'true'. The only child, arranged to the left, is labeled Counter with a state bubble labeled 'count' and value 0. All of the left child is highlighted in yellow, indicating it was added.">
@ -4,7 +4,7 @@ title: 'Referencing Values with Refs'
<Intro>
When you want a component to "remember" some information, but you don't want that information to [trigger new renders](/learn/render-and-commit), you can use a **ref**—it's like a secret "pocket" for storing information in your component!
When you want a component to "remember" some information, but you don't want that information to [trigger new renders](/learn/render-and-commit), you can use a *ref*.
</Intro>
@ -42,7 +42,7 @@ const ref = useRef(0);
<Illustrationsrc="/images/docs/illustrations/i_ref.png"alt="An arrow with 'current' written on it stuffed into a pocket with 'ref' written on it."/>
You can access the current value of that ref through the `ref.current` property. This value is intentionally mutable, meaning you can both read and write to it. (This is what makes it an "escape hatch" from React's one-way data flow--more on that below!)
You can access the current value of that ref through the `ref.current` property. This value is intentionally mutable, meaning you can both read and write to it. It's like a secret pocket of your component that React doesn't track. (This is what makes it an "escape hatch" from React's one-way data flow--more on that below!)
Here, a button will increment `ref.current` on every click:
@ -20,7 +20,7 @@ Before your components are displayed on screen, they must be rendered by React.
Imagine that your components are cooks in the kitchen, assembling tasty dishes from ingredients. In this scenario, React is the waiter who puts in requests from customers and brings them their orders. This process of requesting and serving UI has three steps:
1. **Triggering** a render (delivering the guest's order to the kitchen)
2. **Rendering** the component (getting the order from the kitchen)
2. **Rendering** the component (preparing the order in the kitchen)
3. **Committing** to the DOM (placing the order on the table)
React lets you add event handlers to your JSX. Event handlers are your own functions that will be triggered in response to user interactions like clicking, hovering, focusing on form inputs, and so on.
React lets you add *event handlers* to your JSX. Event handlers are your own functions that will be triggered in response to interactions like clicking, hovering, focusing form inputs, and so on.
</Intro>
@ -67,7 +67,7 @@ You defined the `handleClick` function and then [passed it as a prop](/learn/pas
* Are usually defined *inside* your components.
* Have names that start with `handle`, followed by the name of the event.
> While there is no special syntax for event handlers, it is a convention to name them `handle` followed by the event handled. You'll often see `onClick={handleClick}`, `onMouseEnter={handleMouseEnter}`, and so on.
> By convention, it is common to name event handlers as `handle` followed by the event name. You'll often see `onClick={handleClick}`, `onMouseEnter={handleMouseEnter}`, and so on.
Alternatively, you can define an event handler inline in the JSX:
@ -4,7 +4,7 @@ title: Sharing State Between Components
<Intro>
Sometimes, you want the state of two components to always change together. To do it, remove state from both of them, move it to their closest common parent, and then pass it down to them via props. This is known as "lifting state up", and it's one of the most common things you will do writing React code.
Sometimes, you want the state of two components to always change together. To do it, remove state from both of them, move it to their closest common parent, and then pass it down to them via props. This is known as *lifting state up,* and it's one of the most common things you will do writing React code.
@ -4,7 +4,7 @@ title: "State: A Component's Memory"
<Intro>
Components often need to change what's on the screen as a result of an interaction. Typing into the form should update the input field, clicking "next" on an image carousel should change which image is displayed, clicking "buy" should put a product in the shopping cart. Components need to "remember" things: the current input value, the current image, the shopping cart. In React, this kind of component-specific memory is called **state**.
Components often need to change what's on the screen as a result of an interaction. Typing into the form should update the input field, clicking "next" on an image carousel should change which image is displayed, clicking "buy" should put a product in the shopping cart. Components need to "remember" things: the current input value, the current image, the shopping cart. In React, this kind of component-specific memory is called *state*.
</Intro>
@ -333,9 +333,9 @@ button {
### Meet your first Hook {/*meet-your-first-hook*/}
In React, `useState`, as well as any other function starting with "`use`," is called a **Hook**.
In React, `useState`, as well as any other function starting with "`use`," is called a Hook.
Hooks are special functions that are only available while React is [rendering](/learn/render-and-commit#step-1-trigger-a-render) (which we'll get into in more detail on the next page). They let you "hook into" different React features.
*Hooks* are special functions that are only available while React is [rendering](/learn/render-and-commit#step-1-trigger-a-render) (which we'll get into in more detail on the next page). They let you "hook into" different React features.
State is just one of those features, but you will meet the other Hooks later.
Arrays are another type of mutable JavaScript objects you can store in state and should treat as immutable. Just like with objects, when you want to update an array stored in state, you need to create a new one (or make a copy of an existing one), and then set state to use the new array.
Arrays are mutable in JavaScript, but you should treat as immutable when you store them in state. Just like with objects, when you want to update an array stored in state, you need to create a new one (or make a copy of an existing one), and then set state to use the new array.
JSX is a syntax extension for JavaScript that lets you write HTML-like markup inside a JavaScript file. Although there are other ways to write components, most React developers prefer the conciseness of JSX, and most codebases use it.
*JSX* is a syntax extension for JavaScript that lets you write HTML-like markup inside a JavaScript file. Although there are other ways to write components, most React developers prefer the conciseness of JSX, and most codebases use it.
Components are one of the core concepts of React. They are the foundation upon which you build user interfaces (UI), which makes them the perfect place to start your React journey!
*Components* are one of the core concepts of React. They are the foundation upon which you build user interfaces (UI), which makes them the perfect place to start your React journey!