Loading feed...

React tutorial for beginners teaches fundamentals interactively

Thursday, October 19, 2023

React tutorial for beginners teaches fundamentals interactively

Introduction to React

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.

What is React?

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:

  • Component-Based - UI built from encapsulated, reusable components
  • Declarative - Design simple views for each state in your application
  • Efficient - Virtual DOM minimizes costly DOM operations by only updating what changed
  • Flexible - Integrate with other libraries seamlessly
  • Scalable - Easily build complex applications with React's modular components

Why Learn React?

There are many benefits to learning and using React. Here are some of the top reasons why React is a highly valuable skill:

  • Huge community behind React makes it future-proof to learn
  • In-demand skill as React is used by many top companies like Facebook, Netflix, Uber, Airbnb, etc.
  • Promotes reusability and modular code by encapsulating logic in reusable components
  • Declarative view rendering improves speed and performance
  • Easy to integrate React into existing projects incrementally
  • Popular for building both web and mobile applications
  • Transferable skills to React Native for native mobile apps
  • React knowledge gives you a competitive edge in the job market

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.

React Core Concepts

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

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:

  • JSX tags represent React elements and components
  • Can embed JS expressions by wrapping in {}
  • Compiles down to React.createElement() functions
  • Preferred by most developers for readability and tooling
  • Not required - React can still be used with plain JavaScript

Overall, JSX provides a concise, familiar syntax for defining React component UIs.

Components

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:

  • Reusable, encapsulated code modules
  • Render UI and manage state
  • Accept input as props
  • Return React elements, typically JSX
  • Can be functions or classes
  • Compose to build complex UIs

Components promote separation of concerns for maintainable code.

Props and State

Props and state are core concepts that allow React components to be dynamic and interactive.

Props

  • Read-only data passed to component as attributes
  • Accessed in functions via props parameter
  • Accessed in classes via this.props
  • Changes trigger re-render of component
  • Allow passing data to customize component

State

  • Local, mutable data within a component
  • Defined with useState hook in functions
  • Defined with this.state in classes
  • Changes with setState() trigger re-render
  • Allows components to dynamically update UI

For 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.

Hands-on React Coding

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.

Project Setup

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!

First Component

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!

Component State

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!

Advanced React Concepts

As you become comfortable with the basics, let's explore some more advanced React concepts to take your skills to the next level.

useEffect Hook

The useEffect Hook allows components to synchronize side-effects outside the component logic. Some examples include:

  • API calls to load data
  • Subscriptions to external sources
  • Manual DOM mutations

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 Hook

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:

  • Accessing DOM nodes directly
  • Keeping mutable variables like previous state
  • Optimizing performance by manually handling state

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

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.

Building Projects

The best way to reinforce your React knowledge is to build some projects! Here are some ideas:

  • Simple Todo App - Great beginner project to solidify core concepts like components, state, props, hooks, etc.
  • Calculator - Implement math operations and UI buttons. Practice handling events and updating component state.
  • Weather App - Fetch and display weather API data for a given location. Use effects and requests.
  • Calendar - Interactive calendar to add reminders and events. Coordinate dates and build reusable components.
  • Chat App - Real-time chat interface with messaging. Sync messages via websockets.
  • Games - Memory match, tic-tac-toe, or other classic games. Manage game state across components.

Break the project ideas down into reusable React components. For example, a Todo app might have:

  • TodoList - displays list of todo items
  • TodoItem - single todo item component
  • TodoForm - form to add new todos
  • Navbar - navigation bar with filters

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.

Conclusion

Congratulations - you've completed this interactive React tutorial for beginners! You should now feel comfortable with the fundamentals of React.js:

  • Creating and composing React components with JSX
  • Passing dynamic data into components with props
  • Managing local component state with the useState hook
  • Responding to events and user input
  • And much more!

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.