1. What is React?
React is a JavaScript library for building user interfaces. Facebook made React and released it in 2013.
Full lesson: React intro
44 questions about React with short answers and code. Each answer links to a full lesson on this site. Free, with no signup and no ads.
React is a JavaScript library for building user interfaces. Facebook made React and released it in 2013.
Full lesson: React intro
A component is an independent and reusable part of the user interface. React builds the page from many components.
function Hello() {
return <h1>Hello</h1>;
}
Full lesson: React components
Run the create command with the react template. Vite starts fast and gives a good development experience.
npm create vite@latest my-app -- --template react
cd my-app
npm install
npm run dev
Full lesson: React vite
Load the React and ReactDOM scripts from a CDN. Then load Babel to compile JSX in the browser.
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/18.2.0/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/18.2.0/umd/react-dom.production.min.js"></script>
Full lesson: React install cdn
JSX is a syntax extension that looks like XML. Babel compiles JSX into JavaScript code.
const element = <h1>Hello, world!</h1>;
Full lesson: React jsx
You pass data with props. Props are read-only, so the child cannot change them.
function Hello(props) {
return <h1>Hello {props.name}</h1>;
}
<Hello name="Runoob" />
Full lesson: React props
Use the useState hook. The hook returns the current value and a setter function.
const [count, setCount] = useState(0);
Full lesson: React hooks
Use the style attribute with a JavaScript object. Write each property name in camelCase.
<h1 style={{ color: "red" }}>Hello Style!</h1>
Full lesson: React css
Use the fetch API inside the useEffect hook. The hook runs the request after the component renders.
useEffect(() => {
fetch("/api/data")
.then(res => res.json())
.then(data => setData(data));
}, []);
Full lesson: React ajax
Use the useRef hook to create a ref. Attach the ref to the element and read the current property.
const inputRef = useRef(null);
<input ref={inputRef} />
Full lesson: React refs
Install a router library and wrap the application in a router. Then define a route for each page.
<BrowserRouter>
<Routes>
<Route path="/" element={<Home />} />
</Routes>
</BrowserRouter>
Full lesson: React router
Wrap the component with React.memo. React skips the render when the props do not change.
const MyComponent = React.memo((props) => {
return <div>{props.text}</div>;
});
Full lesson: React memo
You must call the setter function to change state. A direct change to the variable does not trigger a render.
// wrong
count = count + 1;
// right
setCount(count + 1);
Full lesson: React state
Props are read-only, so a child must not change them. The parent must update the data and pass it down again.
// wrong
props.name = "New";
Full lesson: React props
The useEffect hook runs after each render when you omit the dependency array. Add an empty array to run the request one time.
// wrong
useEffect(() => { fetchData(); });
// right
useEffect(() => { fetchData(); }, []);
Full lesson: React ajax
Run the create-react-app command to make a new project. Then start the development server.
npx create-react-app my-app
cd my-app
npm start
Full lesson: React install
Run the npm create vite command with the react template. Then install the dependencies and start the server.
npm create vite@latest my-app -- --template react
cd my-app
npm install
npm run dev
Full lesson: React vite
The src folder holds your source code. The public folder holds static files. The package.json file lists the project dependencies.
Full lesson: React project intro
Pass props as attributes when you use the component. Read them from the props object inside the component. Props are read-only.
function Hello(props) {
return <h1>Hello, {props.name}</h1>;
}
<Hello name="Alice" />
Full lesson: React props
Set the initial state in the constructor. Use this.setState to update the state. React re-renders the component after the update.
class Counter extends React.Component {
state = { count: 0 };
render() { return <p>{this.state.count}</p>; }
}
Full lesson: React state
Call useState with the initial value. It returns the current state and a function to update it.
const [count, setCount] = useState(0);
Full lesson: React hooks
Pass a function to useEffect. The function runs after the component renders. Use the dependency array to control when it runs.
useEffect(() => {
console.log('rendered');
}, []);
Full lesson: React hooks
Make one component for each part of the page. Pass data and callbacks with props. This makes the code easier to maintain.
Full lesson: React blog props
Install the sass package with npm. Then import .scss files in your components. Sass adds variables and nested rules to CSS.
npm i sass
Full lesson: React sass
Install Tailwind CSS and its dependencies. Then add the Tailwind directives to your CSS file. Use utility classes in your JSX.
Full lesson: React tailwind
Use ReactDOM.createRoot to create a root. Then call root.render with your component.
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<App />);
Full lesson: React ref render
Visit the generator website and log in. Enter your app idea in the input box. The tool generates the code for you.
Full lesson: React online
React uses the index as the key by default. When the order changes, React reuses the wrong elements. Use a stable id as the key instead.
items.map(item => <li key={item.id}>{item.name}</li>)
Full lesson: React reference
React compares state by reference. A direct change keeps the same reference, so React does not re-render. Create a new object when you update state.
setUser({ ...user, name: 'Bob' });
Full lesson: React state
Hooks must run in the same order on every render. A condition can change the order. Call Hooks at the top level of the component.
Full lesson: React hooks
The React reference manual lists core APIs, Hooks, and lifecycle methods. It covers basic to advanced topics for React 18 and later.
Full lesson: React reference
JSX looks like HTML and compiles to React.createElement calls. It must have one root element. You can use a fragment to group elements.
return <div>Hello</div>;
Full lesson: React reference
Use curly braces to embed a JavaScript expression in JSX. You can put only expressions inside the braces, not statements.
<h1>{name.toUpperCase()}</h1>
Full lesson: React reference
React components are function components and class components. A function component returns a React element, usually JSX.
function Hello() {
return <h1>Hello, World!</h1>;
}
Full lesson: React components
Small components are easier to maintain and reuse. Each component does one thing. They combine to build complex features.
Full lesson: React blog props
Split a page area into a component when it has independent functionality. For example, make a navigation bar a component because every page needs it.
Full lesson: React blog props
Pass a function as a prop from the parent to the child. The child calls the function to send data back to the parent.
function Child({ onSend }) {
return <button onClick={() => onSend('hi')}>Send</button>;
}
Full lesson: React blog props
ReactDOM.createRoot and root.render replaced ReactDOM.render in React 18. The new API gives better performance.
Full lesson: React ref render
Put reusable components in a components folder. Keep App.jsx small and import the components into it.
src/
├── components/
│ ├── NavBar.jsx
│ └── BlogCard.jsx
└── App.jsx
Full lesson: React blog props
JSX must have a single root element. If you return two elements side by side, the code fails. Wrap them in a fragment or a div.
return (
<>
<h1>Title</h1>
<p>Text</p>
</>
);
Full lesson: React reference
JSX braces accept only expressions, not statements. A statement such as an if block causes an error. Use a ternary expression instead.
<p>{isReady ? 'Ready' : 'Wait'}</p>
Full lesson: React reference
A component must be used as a JSX element, not called like a plain function. Calling it directly skips React features such as state and Hooks. Use JSX syntax to render it.
// Wrong: Hello()
// Right:
<Hello />
Full lesson: React components
Props are read-only in the child component. If the child changes a prop, React does not track the change. Send an event callback to the parent and let the parent change the data.
function Child({ value, onChange }) {
return <button onClick={() => onChange(value + 1)}>+1</button>;
}
Full lesson: React blog props
The root.render call needs ReactDOM. If you do not import ReactDOM, the code fails and the page stays blank. Import ReactDOM before you create the root.
import ReactDOM from 'react-dom/client';
Full lesson: React ref render