Tech Decoded
Search Button
Blog Cover Image

Getting Started with React: A Beginner’s Guide

13 February 2024

By Anthony Jones

React is a popular JavaScript library for building user interfaces. It was created by Facebook in 2013 and has since been used by many companies and developers to create dynamic and interactive web applications. React is based on the concept of components, which are reusable pieces of code that can render UI elements, handle user interactions, and manage state. React also uses a virtual DOM, which is a representation of the actual DOM in memory, to optimize performance and avoid unnecessary re-rendering of the UI.

 

If you are new to React, you might be wondering how to get started and what are the basics you need to learn. In this article, I will give you an introduction to React and show you how to create a simple React app using the create-react-app tool. I will also explain some of the key concepts and features of React, such as JSX, props, state, hooks, and lifecycle methods. By the end of this article, you should have a better understanding of what React is, how it works, and how to use it to build your own web applications.

 

What is JSX?

 

JSX stands for JavaScript XML, and it is a syntax extension that allows you to write HTML-like code in your JavaScript files. JSX makes it easier to create and manipulate UI elements in React, as you can use familiar HTML tags and attributes to define your components. For example, here is a simple JSX element that renders a heading with some text:

 

<h1>Hello, world!</h1>

 

JSX is not valid JavaScript, so it needs to be compiled into plain JavaScript before it can run in the browser. This is done by a tool called Babel, which is included in the create-react-app setup. Babel transforms JSX into React.createElement() calls, which create React elements that can be rendered to the DOM. For example, the JSX element above is equivalent to this JavaScript code:

 

React.createElement("h1", null, "Hello, world!");

 

You can use JSX to define your own custom components, as well as the built-in HTML elements. You can also use JavaScript expressions inside JSX, by wrapping them in curly braces. For example, here is a JSX element that renders a greeting based on a name variable:

 

const name = "John";

<h1>Hello, {name}!</h1>

 

You can learn more about JSX and its syntax rules from the official documentation.

 

What are props?

 

Props are short for properties, and they are the way to pass data from one component to another. Props are like attributes that you can pass to your components when you use them. For example, here is a component that renders a greeting based on a name prop:

 

function Greeting(props) {

return <h1>Hello, {props.name}!</h1>;

}

 

You can use this component in another component and pass a name prop to it:

 

function App() {

return <Greeting name="John" />;

}

 

This will render <h1>Hello, John!</h1> to the DOM. You can pass any type of data as props, such as strings, numbers, arrays, objects, functions, etc. You can also pass multiple props to a component, by using multiple attributes. For example, here is a component that renders a person’s name and age based on two props:

 

function Person(props) {

return (

<div>

<p>Name: {props.name}</p>

<p>Age: {props.age}</p>

</div>

);

}

 

You can use this component in another component and pass both name and age props to it:

 

function App() {

return <Person name="John" age={25} />;

}

 

This will render <div><p>Name: John</p><p>Age: 25</p></div> to the DOM. Props are read-only, which means you cannot modify them inside your components. If you want to change the data that is passed to your components, you need to use state.

 

What is state?

 

State is the way to manage dynamic data in your components. State is an object that contains the data that affects the rendering of your components. Unlike props, state is local and mutable, which means you can change it inside your components. To use state in your components, you need to use a feature called hooks.

 

Hooks are special functions that let you use state and other React features in your functional components. Before hooks were introduced in React 16.8, you had to use class components to use state and other features, such as lifecycle methods. Hooks simplify the code and make it easier to reuse logic across components.

 

The most basic hook is useState, which lets you declare a state variable and a function to update it. For example, here is a component that renders a counter based on a count state variable:

 

import React, { useState } from "react";

function Counter() {

// Declare a state variable called count and a function to update it

const [count, setCount] = useState(0);

return (

<div>

<p>You clicked {count} times</p>

<button onClick={() => setCount(count + 1)}>Click me</button>

</div>

);

}

 

The useState hook takes an initial value as an argument and returns an array with two elements: the current state value and a function to update it. You can use any name for the state variable and the update function, but it is a common convention to use the same name with a set prefix for the function. You can use the update function to change the state value by passing a new value to it. The update function will trigger a re-render of the component with the new state value.

 

You can use multiple state variables in your components, by using multiple useState calls. For example, here is a component that renders a form with two inputs based on two state variables:

 

import React, { useState } from "react";

 

function Form() {

// Declare two state variables: name and email

const [name, setName] = useState("");

const [email, setEmail] = useState("");

 

return (

<form>

<label>

Name:

<input

type="text"

value={name}

onChange={(e) => setName(e.target.value)}

/>

</label>

<label>

Email:

<input

type="email"

value={email}

onChange={(e) => setEmail(e.target.value)}

/>

</label>

<button type="submit">Submit</button>

</form>

);

}

 

The useState hook can also take a function as an argument, which will be executed only once when the component is mounted. This is useful when the initial state value depends on some expensive computation or external data. For example, here is a component that renders a random number based on a state variable that is initialized with a function:

 

import React, { useState } from "react";

 

function Random() {

// Declare a state variable called number and initialize it with a function

const [number, setNumber] = useState(() => Math.floor(Math.random() * 100));

 

return (

<div>

<p>The random number is {number}</p>

<button onClick={() => setNumber(Math.floor(Math.random() * 100))}>

Generate another number

</button>

</div>

);

}

 

You can learn more about state and hooks from the official documentation.

 

What are lifecycle methods?

 

Lifecycle methods are special methods that are invoked at different stages of a component’s life. They allow you to perform some actions or side effects when a component is mounted, updated, or unmounted. For example, you can use lifecycle methods to fetch data from an API, set up timers, subscribe to events, or clean up resources.

 

Before hooks were introduced, you had to use class components to use lifecycle methods. Class components have several lifecycle methods, such as componentDidMount, componentDidUpdate, and componentWillUnmount, that correspond to different phases of the component’s life. For example, here is a class component that fetches a joke from an API and displays it on the screen:

 

import React, { Component } from "react";

 

class Joke extends Component {

constructor(props) {

super(props);

// Initialize the state with an empty joke

this.state = {

joke: "",

};

}

 

// Fetch a joke from the API when the component is mounted

componentDidMount() {

fetch("https://official-joke-api.appspot.com/random_joke")

.then((response) => response.json())

.then((data) => {

// Update the state with the joke

this.setState({

joke: data.setup + " " + data.punchline,

});

});

}

render() {

return <p>{this.state.joke}</p>;

}

}

 

The componentDidMount method is called after the component is rendered for the first time. It is a good place to fetch data from an API, as the component has already been mounted to the DOM and can display the data. The componentDidUpdate method is called after the component is updated, which means its props or state have changed. It is a good place to perform some actions based on the new props or state, such as updating the UI or making another API call. The componentWillUnmount method is called before the component is removed from the DOM. It is a good place to clean up any resources that the component has created, such as timers, subscriptions, or 

listeners. For example, here is a class component that sets up a timer and displays the current time on the screen:

 

import React, { Component } from "react";

 

class Clock extends Component {

constructor(props) {

super(props);

// Initialize the state with the current time

this.state = {

time: new Date().toLocaleTimeString(),

};

}

// Set up a timer when the component is mounted

componentDidMount() {

// Store the timer ID in a class field

this.timerID = setInterval(() => {

// Update the state with the current time every second

this.setState({

time: new Date().toLocaleTimeString(),

});

}, 1000);

}

 

// Clear the timer when the component is unmounted

componentWillUnmount() {

// Use the timer ID to clear the interval

clearInterval(this.timerID);

}

 

render() {

return <p>The current time is {this.state.time}</p>;

}

}

 

The componentWillUnmount method is called before the component is removed from the DOM. It is a good place to clean up any resources that the component has created, such as timers, subscriptions, or listeners. In this case, we use the timer ID to clear the interval and stop the timer.

 

However, with hooks, you can use lifecycle methods in your functional components as well. The hook that lets you do this is useEffect, which lets you perform side effects in your components. The useEffect hook takes a function as an argument, which will be executed after the component is rendered. You can also pass an optional array of dependencies, which tells React when to re-run the effect. For example, here is a functional component that fetches a joke from an API and displays it on the screen, using the useEffect hook:

 

import React, { useState, useEffect } from "react";

function Joke() {
  // Declare a state variable called joke and a function to update it
  const [joke, setJoke] = useState("");

  // Use the useEffect hook to fetch a joke from the API
  useEffect(() => {
    fetch("https://official-joke-api.appspot.com/random_joke")
      .then((response) => response.json())
      .then((data) => {
        // Update the state with the joke
        setJoke(data.setup + " " + data.punchline);
      });
  }, []); // Pass an empty array of dependencies to run the effect only once

  return <p>{joke}</p>;
}

 

The useEffect hook takes a function as an argument, which will be executed after the component is rendered. In this case, we use the fetch API to get a joke from the API and update the state with the joke. We also pass an empty array of dependencies to the useEffect hook, which tells React to run the effect only once, when the component is mounted. This is equivalent to the componentDidMount method in class components.

 

If you want to run the effect more than once, you can pass some values to the array of dependencies, which will tell React to re-run the effect whenever those values change. For example, here is a functional component that sets up a timer and displays the current time on the screen, using the useEffect hook:

 

import React, { useState, useEffect } from "react";

function Clock() {
  // Declare a state variable called time and a function to update it
  const [time, setTime] = useState(new Date().toLocaleTimeString());

  // Use the useEffect hook to set up a timer
  useEffect(() => {
    // Define a function to update the time every second
    const tick = () => {
      setTime(new Date().toLocaleTimeString());
    };

    // Set up a timer and store the timer ID in a variable
    const timerID = setInterval(tick, 1000);

    // Return a cleanup function to clear the timer
    return () => {
      clearInterval(timerID);
    };
  }, []); // Pass an empty array of dependencies to run the effect only once

  return <p>The current time is {time}</p>;
}

 

The useEffect hook takes a function as an argument, which will be executed after the component is rendered. In this case, we define a function to update the time every second and set up a timer using the setInterval function. We also store the timer ID in a variable, which we will use later to clear the timer. We also return a cleanup function from the effect function, which will be executed before the component is unmounted. In this case, we use the clearInterval function to clear the timer using the timer ID. We also pass an empty array of dependencies to the useEffect hook, which tells React to run the effect only once, when the component is mounted. This is equivalent to the componentDidMount and componentWillUnmount methods in class components.

 

You can learn more about lifecycle methods and useEffect from the official documentation.

 

Conclusion

 

In this article, I have given you an introduction to React and showed you how to create a simple React app using the create-react-app tool. I have also explained some of the key concepts and features of React, such as JSX, props, state, hooks, and lifecycle methods. I hope this article has helped you to get started with React and understand how it works and how to use it to build your own web applications.

 

React is a powerful and versatile library that can help you create amazing user interfaces with ease. However, there is much more to learn and explore about React, such as routing, testing, custom hooks, context, reducers, and more. If you want to learn more about React, I recommend you to check out the official documentation, which has a lot of useful information and tutorials. You can also find many online courses, books, blogs, and videos that can teach you more about React and help you improve your skills.

 

ABOUT US

Your source for the latest tech news, guides, and reviews.

Tech Decoded

PAGES

CONTACT

INFORMATION

Receive Tech Decoded's Newsletter in your inbox every week.

NEWSLETTER

Send
Send
You are now a subscriber. Thank you!
Please fill all required fields!

Copyright © 2024 Tech Decoded, All rights reserved.