Programming
October 19, 2023
10 min read
React is a popular JavaScript library created by Facebook for building fast, interactive user interfaces. Since its open source release in 2013, React has been widely adopted by companies like Netflix, Airbnb, and Instagram to power their web and mobile applications.
React's component-based architecture, declarative programming style, and use of a virtual DOM make it an efficient choice for building complex, high-performance user experiences. This article will provide a step-by-step, hands-on React tutorial tailored specifically for beginners looking to learn React fundamentals in an interactive coding environment.
React is an open source JavaScript library used for building user interfaces. It was created internally by Facebook in 2011 and first deployed on Facebook's News Feed in 2011. In 2013, React was open sourced and now maintains over 150,000 stars on GitHub.
React focuses solely on building the view layer of web and mobile applications. It introduces a component-based paradigm where User Interfaces are broken down into reusable, declarative components. React uses a Virtual DOM to optimize updates and only re-render parts of the UI that have changed. This makes React very performant compared to traditional MVC frameworks that re-render the entire page.
Some key characteristics and features of React include:
There are many benefits to learning and using React. Here are some of the top reasons why React is a highly valuable skill:
With its growing popularity and usage, React is a must-learn skill for any front-end web developer. The interactive tutorial ahead on Learn JavaScript will teach you React fundamentals in a practical manner.
Now that you know what React is and why it matters, let's dive into some of the foundational concepts that make React work under the hood.
JSX is an XML/HTML-like syntax extension for JavaScript that allows writing React UI components in an intuitive, declarative style. Although using JSX is optional, it makes representing complex UIs much easier.
For example:
const element = <h1>Hello, world!</h1>;
This JSX code compiles into the following JavaScript:
const element = React.createElement('h1', null, 'Hello, world!');
Under the hood, JSX code compiles down to regular JavaScript function calls and objects. Some key things to know about JSX:
{}
React.createElement()
functionsOverall, JSX provides a concise, familiar syntax for defining React component UIs.
Components are the core building blocks of React applications. A React component is a reusable, self-contained module that encapsulates UI logic and state.
Components allow splitting complex UIs into smaller, manageable pieces. Conceptually, components are like JavaScript functions - they accept input data (called props) and return React elements.
For example, we could define a TodoItem
component:
function TodoItem(props) {
return <li>{props.text}</li>;
}
And use it like:
<TodoItem text="Buy groceries" />
Some characteristics of React components:
Components promote separation of concerns for maintainable code.
Props and state are core concepts that allow React components to be dynamic and interactive.
Props
props
parameterthis.props
State
useState
hook in functionsthis.state
in classessetState()
trigger re-renderFor example, we can create a Counter
component that uses the useState
hook to track a count:
function Counter() {
const [count, setCount] = useState(0);
return (
<div>
<p>You clicked {count} times</p>
<button onClick={() => setCount(count + 1)}>
Click me
</button>
</div>
);
}
Props and state allow creating reusable components that manage their own data and rendering.
Now that we've covered some core concepts, let's start writing some code to learn React hands-on. We'll build a simple React app from scratch and learn key concepts through practical examples.
To use React, we first need to configure some build tools. Let's initialize a project and install React:
# Initialize project
npm init -y
# Install React dependencies
npm install react react-dom
We'll also need Babel to compile our JSX code down to regular JavaScript that browsers understand. Let's install the babel compiler and preset-react plugin:
npm install @babel/core @babel/cli @babel/preset-react --save-dev
Babel will transpile our modern JSX syntax to browser-compatible JavaScript.
In our package.json, let's add a "build" script that will run Babel:
"scripts": {
"build": "babel src -d lib"
}
Now our project is set up to use React and JSX!
Let's create our first React component. Components are usually defined in .js
files.
src/Hello.js
function Hello() {
return <h1>Hello World!</h1>;
}
export default Hello;
This defines a simple Hello
component that returns some JSX. Now let's render it:
src/index.js
import React from 'react';
import ReactDOM from 'react-dom';
import Hello from './Hello';
ReactDOM.render(<Hello />, document.getElementById('root'));
We import React, ReactDOM
, and our Hello
component. Then ReactDOM.render()
mounts the component to the DOM.
Running npm run build
compiles our JSX code down to JS. Then we can open index.html to see "Hello World" rendered!
Let's make our component more interactive by tracking state. React provides a useState
hook that will allow our function component to have state:
function Hello() {
const [name, setName] = useState('World');
return (
<div>
<h1>Hello {name}!</h1>
<input
type="text"
onChange={e => setName(e.target.value)}
/>
</div>
);
}
Now our component renders a name based on state. The input allows updating that state which re-renders the component.
This is just a small taste of React coding. We'll continue exploring more interactive components, props, events, effects, and much more on Learn JavaScript!
As you become comfortable with the basics, let's explore some more advanced React concepts to take your skills to the next level.
The useEffect
Hook allows components to synchronize side-effects outside the component logic. Some examples include:
Use effects take a callback function that contains the side effect code. By default, effects run after every render but this can be customized.
Effects also allow cleaning up after themselves when the component unmounts via a returned cleanup function. This prevents things like memory leaks.
useEffect(() => {
// Run side effect
return () => {
// Cleanup
};
}, [dependencies]);
For example, we could fetch API data with useEffect
:
useEffect(() => {
fetchAPIData();
return () => {
// Cancel API request
}
}, []);
useEffect
is a powerful way to manage side effects in components.
useRef
provides access to the underlying DOM node in a component. This can be useful when you need to imperatively modify the DOM or save a persistent value that doesn't trigger re-renders.
Some common use cases:
useRef
returns an object with a current
property that is initialized to the passed argument (or null
). The object will persist across renders but current
can be modified.
For example:
const ref = useRef(null);
// Later...
ref.current = newValue;
In general, useRef
can be used instead of useState
when you don't need triggers re-renders after updates.
React Context provides a way to share data globally across components without passing props down manually.
First, create a Context object:
const UserContext = React.createContext();
Then, provide a value for the context:
<UserContext.Provider value={user}>
{/* Child components */}
</UserContext.Provider>
Finally, consume the context in descendants with the useContext
hook:
const user = useContext(UserContext);
Context is great for global data like current user, theme, or language. It helps avoid prop drilling.
The best way to reinforce your React knowledge is to build some projects! Here are some ideas:
Break the project ideas down into reusable React components. For example, a Todo app might have:
Think about the architecture and data flow. What state and props do components need? Where should shared state live?
React projects give you a chance to apply your new skills in a realistic environment. They also give you something impressive to show off to friends, family, employers, etc. The interactive lessons on Learn JavaScript provide guided projects to reinforce your React skills.
Congratulations - you've completed this interactive React tutorial for beginners! You should now feel comfortable with the fundamentals of React.js:
This tutorial provided a hands-on coding introduction to build a solid React foundation. From here, you can continue growing your skills. Learn JavaScript offers many more advanced React tutorials and courses to take your learning to the next level.
React is an invaluable skill for modern web development. With this tutorial under your belt, you're well on your way to mastering React! Let us know in the comments what React topics you want to learn next.