Programming
October 19, 2023
10 min read
React has exploded in popularity as the go-to JavaScript library for building modern user interfaces. Created and open sourced by Facebook in 2013, React focuses exclusively on the view layer of web and mobile apps. With its declarative, component-based architecture, React allows you to build reusable UI components that can be composed together to create complex and interactive web applications.
Some of the key advantages that have made React so popular include:
This comprehensive tutorial will teach you React fundamentals step-by-step from the ground up. You'll learn about JSX, components, props, state, hooks, routing, APIs, state management, and more through practical examples. By the end, you'll be ready to build real-world React applications.
React is an open-source JavaScript library created and maintained by Facebook. It focuses exclusively on the view layer of web and mobile apps - the user interface. Because of this focused scope, React integrates really well with other libraries and frameworks to build full-stack apps.
Some key features of React include:
Overall, React focuses exclusively on building reusable UI components that can be composed to create complex and dynamic web UIs. It's incredibly popular because of its simplicity, flexibility, and performance. Major companies like Facebook, Netflix, Airbnb, Uber, and Instagram use React for their most complex products and apps.
There are many advantages that make React one of the most popular UI libraries:
Overall, React is fast, reusable, flexible, and scales really well. Its growing community makes it a great choice for building production web apps.
Here are some of the topics we'll be covering in this React tutorial for beginners:
By the end of this comprehensive tutorial, you'll have the skills to build production-ready apps and websites using modern React. Let's get started!
React is built around some key concepts like JSX, components, props, state, and hooks that enable creating declarative UIs. Let's go through each of these React fundamentals.
JSX is a syntax extension for JavaScript that React uses to describe what a UI should look like. It may look like HTML, but it has the full power of JavaScript behind it.
Some things to note about JSX:
{}
.Overall, JSX provides an intuitive visual representation of component UIs while leveraging the power of JavaScript.
Components are reusable building blocks for React apps. Components manage their own state and rendering.
There are two types of components:
React.Component
.Components can render UI, handle user input, communicate with APIs, and more. Complex UIs are built by composing components in a hierarchy.
Here's an example of a simple Function component:
function Welcome(props) {
return <h1>Hello, {props.name}</h1>;
}
And using it:
<Welcome name="Sara" />
Props (properties) are inputs to React components. They allow passing data into components:
For example, we can pass a title
prop to a <Header>
component to dynamically set the header text:
<Header title="Welcome" />
The useState
hook is a function that lets you add state to React function components.
Calling useState
declares a state variable. It returns an array with the current state value and a function to update it:
const [count, setCount] = useState(0);
You can pass the initial state as an argument to useState()
. The state setter function can be used to update the state.
Other commonly used hooks include useEffect
, useContext
, useReducer
etc.
Now that you understand the fundamentals, let's go over how to build UI components and structure React apps.
There are two types of components:
This separation of concerns keeps components clean and reusable.
For example, a <Profile/>
component that displays a user profile could be a presentational component while the <ProfilePage/>
component that fetches the user data and passes it down could be a container.
React UIs are built using a component tree. The root component renders major page sections which further render child components for smaller parts.
For example, a <Page>
component can render a <Header>
, <Content>
, and <Footer>
. The <Content>
can have many nested subcomponents.
function Page() {
return (
<div>
<Header />
<Content>
<NewsFeed />
<Ads />
</Content>
<Footer />
</div>
)
}
Forms, buttons, and other input elements can be created using regular HTML in JSX. Use state to handle form input and submissions.
For example:
function Form() {
const [name, setName] = useState('');
function handleSubmit(e) {
e.preventDefault();
alert(`Hello ${name}!`)
}
return (
<form onSubmit={handleSubmit}>
<input
value={name}
onChange={e => setName(e.target.value)}
/>
<button type="submit">Submit</button>
</form>
)
}
We can manage the form value in state and submit the form to show an alert.
As you get comfortable with the basics, here are some advanced React concepts:
Custom hooks allow you to extract component logic into reusable functions. For example:
function useFetch(url) {
const [data, setData] = useState(null);
// ...fetch data and update state
return data;
}
HOCs are functions that take a component and returns a new enhanced component:
function withAuth(Component) {
return props => {
// ...logic to check auth
return <Component {...props} />
}
}
React context allows passing data without prop drilling:
const UserContext = React.createContext();
const App = () => {
return (
<UserContext.Provider value={user}>
<Page />
</UserContext.Provider>
)
}
Error boundaries allow you to gracefully handle component errors.
Portals provide a way to render children into different DOM nodes like popups:
render() {
return ReactDOM.createPortal(
<Modal />,
document.body
);
}
Let's go over some tools and libraries commonly used in React apps:
Create React App configures and sets up React projects without any build configuration needed. To start a new app:
npx create-react-app my-app
cd my-app
npm start
It includes Babel, ESLint, Jest, and other tools preconfigured so you can focus on writing React code.
React Router enables client-side routing in React. It allows creating multi-page UIs with navigation without page refreshes:
<BrowserRouter>
<Link to="/">Home</Link>
<Route path="/" exact component={Home} />
<Route path="/about" component={About} />
</BrowserRouter>
The Axios library is commonly used to make HTTP requests from React:
async function getUsers() {
try {
const response = await axios.get('/api/users');
console.log(response.data);
} catch (error) {
console.log(error);
}
}
You can GET
, POST
, and more with Axios.
For complex apps, Redux helps manage state in a central store. Components dispatch actions that trigger state updates.
// Action
{ type: 'counter/increment' }
// Reducer
function counterReducer(state, action) {
// ...update state
}
Recoil is a newer state management library that works well with React.
Platforms like Vercel and Netlify make deployment easy through continuous integration with GitHub. They auto-generate production builds.
I hope this React tutorial gave you a comprehensive introduction to React fundamentals and building real-world applications. React is an incredibly powerful tool for crafting UIs.
The key concepts include:
You can now take these skills to build interactive web apps. Check out the tutorials and interactive lessons on Learn JavaScript for more on mastering React and modern web development.