🗓️ Schedule your free AI consultation with us now 💼
Published Oct 19, 2023 ⦁ 10 min read
React JS Tutorial for Beginners Teaches You Modern React From Scratch

React JS Tutorial for Beginners Teaches You Modern React From Scratch

Introduction to React JS

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:

  • React lets you build encapsulated components that manage their own state. This makes it easy to reason about your UI and debug.
  • React uses a declarative approach that makes your code more predictable and maintainable. You simply declare what each component should render.
  • React apps are fast and scalable. Its use of a virtual DOM means rendering is extremely fast at scale. Apps feel responsive.
  • React code is easy to understand thanks to its component structure. Complex UIs can be broken down into simple reusable parts.

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.

What is React?

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:

  • Component-based architecture - React apps are built using small modular and reusable components. Components manage their own state and rendering.
  • Declarative UI programming - React uses a declarative paradigm that makes it easier to reason about your app. You simply declare what each component should render.
  • Efficient updates - React only updates components when the underlying data changes. This makes rendering very fast and efficient. Apps feel responsive.
  • One-way data binding - Data in React apps follows a one-way directional flow downwards from parent to child components. This makes the logic very predictable.

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.

Why Use React?

There are many advantages that make React one of the most popular UI libraries:

  • React has a strong community behind it and is used by companies like Facebook, Instagram, Netflix, Airbnb, and more. This means there are tons of resources available to learn React.
  • For most apps, React offers better performance than traditional frameworks because of its virtual DOM. The UI updates extremely quickly and efficiently.
  • React promotes reusability through composable components. Complex UIs can be broken down into simple reusable parts.
  • React's declarative nature makes code more predictable and easier to debug compared to other UI libraries.
  • React can be used for simple projects but also scales well for large enterprise applications. Companies like Facebook use React for their most complex products.

Overall, React is fast, reusable, flexible, and scales really well. Its growing community makes it a great choice for building production web apps.

What You Will Learn

Here are some of the topics we'll be covering in this React tutorial for beginners:

React Fundamentals

  • JSX syntax - The HTML-like syntax used by React
  • Components - Reusable building blocks
  • Props - Pass data into components
  • State - Add internal data with useState hook
  • Hooks - useState, useEffect, useContext etc

Building UIs

  • Presentational vs container components
  • Component composition - Building component trees
  • Handling user input like forms
  • Updating UI based on state

Advanced Concepts

  • Custom hooks
  • Higher order components
  • Context API - Pass data without prop drilling
  • Error boundaries
  • React portals - Render children outside parent

Real World React Apps

  • Project setup with Create React App
  • Routing with React Router
  • Making API calls with Axios
  • State management with Redux or Recoil
  • Deployment on Vercel and Netlify

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 Fundamentals

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 Syntax

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:

  • JSX code must be compiled to JavaScript using tools like Babel and webpack.
  • You can embed any JavaScript expressions inside JSX using curly braces {}.
  • JSX helps prevent XSS attacks by automatically escaping values.
  • JSX represents UI components, which are encapsulated and reusable pieces of code.

Overall, JSX provides an intuitive visual representation of component UIs while leveraging the power of JavaScript.

React Components

Components are reusable building blocks for React apps. Components manage their own state and rendering.

There are two types of components:

  • Function components are simple JavaScript functions that accept props and return JSX.
  • Class components are ES6 classes that extend 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 in React

Props (properties) are inputs to React components. They allow passing data into components:

  • Components receive props as function parameters.
  • Props are immutable and should not be changed inside components.
  • Components can customize rendering and logic based on the props received.

For example, we can pass a title prop to a <Header> component to dynamically set the header text:

<Header title="Welcome" />

useState Hook

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.

Building UIs in React

Now that you understand the fundamentals, let's go over how to build UI components and structure React apps.

Presentational vs Container Components

There are two types of components:

  • Presentational components focus on UI rendering based on props received.
  • Container components manage data, handle business logic, and pass props to presentational 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.

Component Hierarchy

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>
  )
}

Handling User Input

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.

Advanced React Concepts

As you get comfortable with the basics, here are some advanced React concepts:

Custom Hooks

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;
}

Higher Order Components

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} />
  }
}

Context API

React context allows passing data without prop drilling:

const UserContext = React.createContext(); 

const App = () => {
  return (
    <UserContext.Provider value={user}>
       <Page />
    </UserContext.Provider>
  )
}

Error Boundaries

Error boundaries allow you to gracefully handle component errors.

React Portals

Portals provide a way to render children into different DOM nodes like popups:

render() {
  return ReactDOM.createPortal(
    <Modal />,
    document.body
  );
}

Building Real World React Apps

Let's go over some tools and libraries commonly used in React apps:

Create React App

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

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>

Making API Calls

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.

State Management

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.

Deployment

Platforms like Vercel and Netlify make deployment easy through continuous integration with GitHub. They auto-generate production builds.

Conclusion

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:

  • JSX, components, props, state, hooks for declarative UIs
  • Composing reusable UI components
  • Managing state with context, Redux
  • Tools like React Router, Axios, and more

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.

Related posts