In this guide, I’ll introduce you to React and several of its fundamental concepts. We’ll get up and running quickly with the Create React App tool, then we’ll walk step-by-step through the process of building out a simple React application. By the time you’re finished, you’ll have a good overview of the basics and will be ready to take the next step on your React journey.
To follow along with this tutorial, you’ll need both Node and npm installed on your machine. To do this, head to the Node.js download page and grab the version you need (npm comes bundled with Node). Alternatively, you can consult our tutorial on installing Node using a version manager.
What is React?
function keyword. Class-based components will implement a
React components can further be categorized into stateful and stateless components. A stateless component’s work is simply to display data that it receives from its parent React component. If it receives any events or inputs, it can simply pass these up to its parent to handle.
A stateful component, on the other hand, is responsible for maintaining some kind of application state. This might involve data being fetched from an external source, or keeping track of whether a user is logged in or not. A stateful component can respond to events and inputs to update its state.
As a rule of thumb, you should aim to write stateless components where possible. These are easier to reuse, both across your application and in other projects.
Understanding the Virtual DOM
Before we get to coding, you need to be aware that React uses a virtual DOM to handle page rendering. If you’re familiar with jQuery, you know that it can directly manipulate a web page via the HTML DOM. In a lot of cases, this direct interaction poses few if any problems. However, for certain cases, such as the running of a highly interactive, real-time web application, performance can take quite a hit.
To counter this, the concept of the Virtual DOM (an in-memory representation of the real DOM) was invented, and is currently being applied by many modern UI frameworks including React. Unlike the HTML DOM, the virtual DOM is much easier to manipulate, and is capable of handling numerous operations in milliseconds without affecting page performance. React periodically compares the virtual DOM and the HTML DOM. It then computes a diff, which it applies to the HTML DOM to make it match the virtual DOM. This way, React ensures that your application is rendered at a consistent 60 frames per second, meaning that users experience little or no lag.
Start a Blank React Project
As per the prerequisites, I assume you already have a Node environment set up, with an up-to-date version of npm (or optionally Yarn).
Next, we’re going to build our first React application using Create React App, an official utility script for creating single-page React applications.
Let’s install this now:
npm i -g create-react-app
Then use it to create a new React app.
Depending on the speed of your internet connection, this might take a while to complete if this is your first time running the
create-react-app command. A bunch of packages get installed along the way, which are needed to set up a convenient development environment — including a web server, compiler and testing tools.
If you’d rather not install too many packages globally, you can also
npx, which allows you to download and run a package without installing it:
npx i -g create-react-app
Running either of these commands should output something similar to the following:
... Success! Created react-app at C:Usersmikeprojectsgithubmessage-app Inside that directory, you can run several commands: yarn start Starts the development server. yarn build Bundles the app into static files for production. yarn test Starts the test runner. yarn eject Removes this tool and copies build dependencies, configuration files and scripts into the app directory. If you do this, you can’t go back! We suggest that you begin by typing: cd message-app yarn start Happy hacking!
Once the project setup process is complete, execute the following commands to launch your React application:
cd message-app npm start
You should see the following output:
.... Compiled successfully! You can now view react-app in the browser. Local: http://localhost:3000 On Your Network: http://192.168.56.1:3000 Note that the development build is not optimized. To create a production build, use yarn build.
Your default browser should launch automatically, and you should get a screen like this:
Now that we’ve confirmed our starter React project is running without errors, let’s have a look at what’s happened beneath the hood. You can open the folder
message-app using your favorite code editor. Let’s start with
"name": "message-app", "version": "0.1.0", "private": true, "dependencies": "@testing-library/jest-dom": "^4.2.4", "@testing-library/react": "^9.3.2", "@testing-library/user-event": "^7.1.2", "react": "^16.13.1", "react-dom": "^16.13.1", "react-scripts": "3.4.3" , "scripts": "start": "react-scripts start", "build": "react-scripts build", "test": "react-scripts test", "eject": "react-scripts eject" , "eslintConfig": "extends": "react-app" , "browserslist": "production": [ ">0.2%", "not dead", "not op_mini all" ], "development": [ "last 1 chrome version", "last 1 firefox version", "last 1 safari version" ]
As you can see, Create React App has installed several dependencies for us. The first three are related to the React Testing Library which (as you might guess) enables us to test our React code. Then we have
react-dom, the core packages of any React application, and finally
react-scripts, which sets up the development environment and starts a server (which you’ve just seen).
Then come four npm scripts, which are used to automate repetitive tasks:
startstarts the dev server
buildcreates a production-ready version of your app
testruns the tests mentioned above
ejectwill expose your app’s development environment
This final command is worth elaborating on. The Create React App tool provides a clear separation between your actual code and the development environment. If you run
npm run eject, Create React App will stop hiding what it does under the hood and dump everything into your project’s
package.json file. While that gives you a finer grained control over your app’s dependencies, I wouldn’t recommend you do this, as you’ll have to manage all the complex code used in building and testing your project. If it comes to it, you can use customize-cra to configure your build process without ejecting.
Create React App also comes for support with ESLint (as can be seen from the
eslintConfig property) and is configured using react-app ESLint rules.
browserslist property of the
package.json file allows you to specify a list of browsers that your app will support. This configuration is used by PostCSS tools and transpilers such as Babel.
For now, let’s first stop the development server by pressing Ctrl + C. Once the server has stopped, delete everything except the
setupTests.js files in the
src folder. If you’re interested in finding out what service workers do, you can learn more about them here.
Other than that, we’ll create all the code from scratch so that you can understand everything inside the
Introducing JSX Syntax
Here’s a quick example:
import React from 'react'; export default function App() const message = <h1>I'm a heading</h1>; //JSX FTW! return ( message );
Notice the line
Note: you can learn more about JSX in our tutorial “An Introduction to JSX”.
In the past, React JSX files used to come with a
.jsx file extension. Nowadays, the Create React App tool generates React files with a
.js file extension. While the
.jsx file extension is still supported, the maintainers of React recommend using
.js. However, there’s an opposing group of React developers, including myself, who prefer to use the
.jsx extension, for the following reasons:
- In VS Code, Emmet works out of the box for
.jsxfiles. You can, however, configure VS Code to treat all
However, for this tutorial, I’ll abide by what Create React App gives us and stick with the
.js file ending.
Hello, World! in React
Let’s get down to writing some code. Inside the
src folder of the newly created
message-app, create an
index.js file and add the following code:
import React from 'react'; import ReactDOM from 'react-dom'; ReactDOM.render(<h1>Hello World</h1>, document.getElementById('root'));
Start the development server again using
npm start or
yarn start. Your browser should display the following content:
This is the most basic “Hello World” React example. The
index.js file is the root of your project where React components will be rendered. Let me explain how the code works:
- Line 1: The React package is imported to handle JSX processing.
- Line 2: The ReactDOM package is imported to render the root React component.
- Line 3: Call to the render function, passing in:
<h1>Hello World</h1>: a JSX element
document.getElementById('root'): an HTML container (the JSX element will be rendered here).
The HTML container is located in the
public/index.html file. On line 31, you should see
<div id="root"></div>. This is known as the root DOM node because everything inside it will be managed by the React virtual DOM.
While JSX does look a lot like HTML, there are some key differences. For example, you can’t use a
className is used in its place. Also, events such as
onclick are spelled
onClick in JSX. Let’s now modify our Hello World code:
const element = <div>Hello World</div>; ReactDOM.render(element, document.getElementById('root'));
I’ve moved the JSX code out into a constant variable named
element. I’ve also replaced the
h1 tags with
div tags. For JSX to work, you need to wrap your elements inside a single parent tag.
Take a look at the following example:
const element = <span>Hello,</span> <span>Jane</span>;
The above code won’t work. You’ll get a syntax error indicating you must enclose adjacent JSX elements in an enclosing tag. Something like this:
const element = <div> <span>Hello, </span> <span>Jane</span> </div>;
const name = "Jane"; const element = <p>Hello, name</p>
… or like this:
const user = firstName: 'Jane', lastName: 'Doe' const element = <p>Hello, user.firstName user.lastName</p>
Update your code and confirm that the browser is displaying “Hello, Jane Doe”. Try out other examples such as
5 + 2 . Now that you’ve got the basics of working with JSX, let’s go ahead and create a React component.
Declaring React Components
The above example was a simplistic way of showing you how
ReactDOM.render() works. Generally, we encapsulate all project logic within React components, which are then passed to the
src folder, create a file named
App.js and type the following code:
import React, Component from 'react'; class App extends Component render() return ( <div> Hello World Again! </div> ) export default App;
React.Component. We’ve also defined a render function that returns a JSX element. You can place additional JSX code within the
<div> tags. Next, update
src/index.js with the following code in order to see the changes reflected in the browser:
import React from 'react'; import ReactDOM from 'react-dom'; import App from './App'; ReactDOM.render(<App/>, document.getElementById('root'));
First we import the
App component. Then we render
App using JSX format, like so:
<App/>. This is required so that JSX can compile it to an element that can be pushed to the
React DOM. After you’ve saved the changes, take a look at your browser to ensure it’s rendering the correct message.
Next, we’ll look at how to apply styling.
Getting Started with React: A Beginner’s Guide