How much JavaScript you need to know to use React?
By Flavio
Published · Updated
Tagged: React
Find out how much JavaScript you need before learning React, from classes and ES modules to arrow functions, destructuring, and the spread operator.
You don’t need to be a JavaScript expert to start with React. But there is a set of modern JavaScript features you’ll use constantly, and knowing them first makes learning React much smoother.
If you are willing to learn React, you first need to have a few things under your belt. There are some prerequisite technologies you have to be familiar with, in particular related to some of the more recent JavaScript features you’ll use over and over in React.
Sometimes people think one particular feature is provided by React, but instead it’s just modern JavaScript syntax. JSX gets the attention, but most of what looks like “React magic” in a codebase is plain JavaScript.
There is no point in being an expert in those topics right away, but the more you dive deep into React, the more you’ll need to master those.
I will mention a list of things, with pointers to articles I wrote that can help you get up to speed quickly:
- JavaScript classes
- ES Modules
- The basics of asynchronous programming: callbacks, promises, async/await
- Arrow functions
- this
- The spread operator
- Destructuring assignments
- Object literals
- Functional programming with JavaScript
Where you’ll meet each one
ES Modules show up at the top of every React file. A component imports what it needs, like a hook from react or another component, and exports itself, using import and export. Since React 17 you don’t need to import React itself just to write JSX.
Arrow functions are everywhere: event handlers, callbacks passed as props, and functions passed to array methods when rendering lists.
Destructuring is how you unpack props. Instead of writing props.name all over the component, you pull the values out once.
The spread operator copies objects and arrays. Since React expects you to never mutate state, you create updated copies instead, and spread is the tool for that.
Here’s a tiny component using several of these at once:
const Profile = ({ name, city }) => {
return <p>{name} lives in {city}</p>
}
That’s an arrow function and destructuring in the parameters. The JSX is React, everything around it is JavaScript.
Classes and this matter for class components, which you’ll find in many existing codebases and tutorials. this in particular trips people up in event handlers, and that’s a JavaScript problem, not a React one. New code uses function components, and the React docs recommend them over classes, so you can learn classes later, when you meet one.
Asynchronous programming comes in as soon as you fetch data from a server. Promises and async/await are how you talk to APIs.
Array methods: map and filter
React has no special syntax for loops. To render a list, you turn an array of data into an array of elements with map():
const TodoList = ({ todos }) => {
return (
<ul>
{todos.map((todo) => (
<li key={todo.id}>{todo.text}</li>
))}
</ul>
)
}
The key is the React part. It tells React which item is which when the list changes. Use a stable ID from your data. The array index works only if the list never gets reordered, filtered or added to in the middle.
filter() comes up just as often, to show part of a list:
{todos.filter((todo) => !todo.done).map((todo) => (
<li key={todo.id}>{todo.text}</li>
))}
Ternaries and && for conditions
You can’t put an if statement inside JSX, because JSX only accepts expressions. So you use the ternary operator and && instead:
<p>{isLoggedIn ? 'Welcome back' : 'Please log in'}</p>
{error && <p className="error">{error}</p>}
&& returns the left side when it’s falsy. That’s a trap with numbers:
{items.length && <ItemList items={items} />}
When the array is empty, items.length is 0, and React renders a 0 on the page. false, null and undefined render nothing, but 0 is a number and React shows it. Make the left side a real boolean:
{items.length > 0 && <ItemList items={items} />}
I cover more patterns in conditional rendering in React.
Updating objects and arrays without mutating them
This is where the spread operator earns its place. When you set state, React compares the new value with the old one using Object.is. If you change an object in place and pass it back, it’s still the same object, so React skips the update and the screen doesn’t change:
// wrong: changes the array React already has
todos.push(newTodo)
setTodos(todos)
Create a new array or object instead:
// add an item
setTodos([...todos, newTodo])
// remove an item
setTodos(todos.filter((t) => t.id !== id))
// change one item
setTodos(todos.map((t) => (t.id === id ? { ...t, done: true } : t)))
// change one property of an object
setUser({ ...user, name: 'Flavio' })
Watch out: spread makes a shallow copy. In { ...user }, a nested object like user.address is still shared with the original. To change it, copy that level too: { ...user, address: { ...user.address, city: 'Rome' } }.
Optional chaining and ??
Data from an API often arrives later, or with missing fields. Reading a property of undefined throws an error and breaks the whole component. Optional chaining ?. stops early and gives you undefined instead, and ?? supplies a fallback:
<p>{user?.address?.city ?? 'Unknown city'}</p>
?? only kicks in for null and undefined. That’s different from ||, which also replaces 0 and the empty string.
Template literals
Template literals come up when you build strings from values, like class names or URLs:
<button className={`button ${isActive ? 'active' : ''}`}>Save</button>
fetch(`/api/users/${userId}`)
Default and named exports
A file can have one default export and many named exports, and you import them differently:
// Button.jsx
export default function Button() { /* ... */ }
export const sizes = ['small', 'large']
// App.jsx
import Button, { sizes } from './Button'
Mixing the two up gives you undefined instead of a component, and an error like “Element type is invalid”. If you see it, check the curly braces in your import first.
My advice: skim these topics now, start React, and come back to each one the moment it confuses you in real code. That’s when it sticks.
Want me to talk about your product? You can sponsor this site.