Understanding React guide for beginners

by Daniel Zsiga, Software Developer

First things first, what is React used for?

It is used for building web applications, its focus being to allow the development of fast user interfaces. React also has variants like React Native for mobile app development.

Who is React for?

If you have a good grasp of CSS, HTML, and JavaScript, meaning you've built a few personal/professional projects, I'd say you can get into React. Having the aforementioned skills checked, will make things easier during the learning process, and you will be able to understand things better. Opting to jump straight into React and skipping the basics could result in you missing out, but feel free to approach things as you see fit.

Who made React?

Created by Jordan Walke, React's development is now led by a dedicated team working full-time at Meta. It also receives contributions from people all over the world.

Read more about this topic.

React Concepts

React is component-based; components are independent and reusable bits of code. They work in isolation and return HTML. This allows us to combine them and build complex elements for our applications. A component can be as simple or as complex as you intend it to be.

There are two types of components in React: class-based and functional. Back when React first came out, class components were the way to go. Nowadays, functional components are more often found in projects. They are easier to read, write, and test. I am not going to cover class-based components in this article, but I will leave links at the end for further reading.

Bellow you can see a simple example of a functional component:

import Hello from "./Hello";

export default function App() {
  return <Hello />;
};

The App component serves as the central hub of our application, orchestrating the various components that comprise the user interface. Typically, you'll encounter a similar structural approach in most React applications.

As you can see creating a component is really simple, just create a file and give it a proper name, in our case "Hello" and write the appropriate syntax. As to not create confusion within your project it is best to call both the file and the function the same name, also components will always start with a capital letter, this helps to distinguish them from normal HTML elements. Go ahead and click on Hello.js in the example above to see the code.

We notice that we are writing HTML in a JavaScript file; what is going on here? This is called JSX. It allows us to seemingly write JavaScript that looks like markup. JSX is syntactic sugar over the actual component syntax, making it more readable. In the end, it gets compiled into something the browser can read. It allows us to do many other cool things, as you will see in later examples. JSX is not mandatory for working with React, as it is not React-specific, but I do recommend using it due to its benefits, and you will find it in most React projects.

Click here to read more about JSX

Moving forward, let's have a look at how we can use multiple components with each other and how data is passed between them:

import "./styles.css";
import { UserInfo } from "./UserInfo";

export default function App() {
  return <UserInfo />;
};

I would like to break down each note worthy information from the components presented above:

  • UserInfo:

    As mentioned before components can be used together, not only that but we can even pass data from the parent component, in our case UserInfo, to the child, the Profile component.

    These are our props:

    firstName, lastName, age and email, these are being passed to Profile as follows:


<Profile
  firstName="Johnny"
  lastName="Cage"
  age={29}
  email="[email protected]"
/>

Worth mentioning that in React, data flows from top to bottom, like here form parrent to child. This allows for better control of our data and due to its predictable nature we are less error prone.

  • Profile:

    Our Profile component accepts props, essentially data passed to it by its parrent, its up to us how we use said data, based on what we are trying to build.

    Now notice how easy it is to just add our variables to HTML thanks to JSX:


return (
  <div className="profile">
    <p>
      User: {firstName} {lastName} is {age} years old.
    </p>
    <p>Email: {email}</p>
  </div>
);

By just using the curly braces we escape HTML and are able to use JavaScript, variables, logic, you name it.

As mentioned, with JSX, we can include logic right inside our markup. Let's have a look at a practical example where we show or hide an element based on a condition:

import "./styles.css";

export default function App() {
  const isItGreen = true;
  return (
    <div className="App">
      {isItGreen ? (
         <div className="green-ball">Green</div>
       ) : (
         <div className="red-ball">Red</div>
       )}
    </div>
  );
}

Based on the variable isItGreen we decide if we want to show a green ball or a red one.

Not only that, but the actual element is not placed in the DOM (Document Object Model) this is called conditional rendering. This actually means that the element is not rendered at all in the DOM, it is not just hidden.

Another thing worth mentioning here is the following code:


{isItGreen ? (
  <div className="green-ball">Green</div>
) : (
  <div className="red-ball">Red</div>
)}

This is called a ternary operator, essentially a shorthand for if-else statements. This simple inline conditional allows us to fluidly write a condition that, based on the value of isItGreen, renders either the "green-ball" or the "red-ball" element. Opting not to use the ternary operator would require us to create a separate function to handle the if-else logic.

Now lets get into something really interactive and cool, State.

Imagine a scenario where you want to allow users to enter their name into an input field. Upon pressing a button, the name or any text they've entered should be displayed on the page. If you've followed along so far and understand components, their combined usage, data passing, and conditional rendering, you're ready to tackle another essential concept in React: State. State is crucial because it allows us to keep track of data and update it when necessary—essentially, it's all about data management.

import { useState } from "react";
import "./styles.css";

export default function App() {
  const [name, setName] = useState("");

  const handleSubmit = (e) => {
    e.preventDefault();
    const newName = e.target["name"].value;
    setName(newName);
    e.target["name"].value = "";
  };

  return (
    <div className="App">
      <h1>Hello, {name}</h1>
      <form className="name-form" onSubmit={handleSubmit}>
        <input
          className="name"
          type="text"
          placeholder="Your name"
          name="name"
        />
        <button className="submit" type="submit">
          Add your name
        </button>
      </form>
    </div>
 );
}

State in React allows us to keep track of changing data in our components. For instance, consider a red button on your webpage. If the button changes color, its 'state' has changed. State changes often occur due to user interactions, like clicking a button.


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

The useState hook is a built-in React function for managing state. It returns two values: the current state and a setter function for updating that state. Whenever the state updates, React knows to re-render the affected components.


const handleSubmit = (e) => {
  e.preventDefault();
  const newName = e.target["name"].value;
  setName(newName);
  e.target["name"].value = "";
};

handleSubmit is our event handler function. In JSX, it's straightforward to attach this function to handle the onSubmit event for our form. When the form is submitted, handleSubmit is automatically called, and the event object is passed to it as a parameter. This allows us to access properties of the event, such as the form fields, and implement any logic we need for form submission.

Let's take a look at another example of State, a classic one, the counter:

import { useState } from "react";
import "./styles.css";

export default function App() {
  const [count, setCount] = useState(1);
  return (
    <div className="counter">
      <h1 className="title">
        The most ancient way of demonstrating state, behold, the counter!
      </h1>
      <h2 className="description">
        Bow before the might of the counter, {count} time{count > 1 ? "s" : ""}!
      </h2>
      <button
        className="bow"
        onClick={() => setCount(count + 1)}
      >
        Increment Bows!
      </button>
    </div>
  );
}

Again, notice the useState Hook method used here. We are initializing it with its default value of 1, and as before, we have a value and a setValue—in this case, count and setCount. One rule that I should mention when using a React Hook is that you should not call it conditionally, or in a loop. This disturbs the tracking order React has for said hooks and may result in unwanted results.


  onClick={() => setCount(count + 1)}

Over here we are essentially taking our current count state adding 1 to it and updating it, and the cycle continues as many times as we press the button.

Now that we are starting to understand how things work (hopefully), let's look at how we handle data fetching and listing multiple components:

import "./styles.css";
import Users from "./Users";

export default function App() {
  return <Users />;
}

Lets talk about the Users component because thats where everything is happening.

Right off the bat we see a new hook, useEffect. it allows us to handle side effects in our React component. Side effects include actions like fetching data from an API, updating the DOM, setting up subscriptions, or any other kind of external interactions. In functional programming terms, a side effect is an operation that interacts with the outside world, altering state outside the scope of the function. While a deeper understanding involves functional programming concepts, knowing that useEffect is essential for operations not directly related to rendering is sufficient for now.


useEffect(() => {
  const fetchUsers = async () => {
    const users = await fetch(url);
    const parsedUsers = await users.json();
    setUsers(parsedUsers);
  };

  fetchUsers();
}, []);

Notice the empty array passed as the second argument to our useEffect function, the first argument being the callback function. This array is called a dependency array. It signals to the function when it should run again. For example, if we wanted to fetch a user by ID and that ID often changes, we would include it inside our dependency array. In our case, we want the function to run only once, on the initial component render and as such we leave it empty.


return (
  <ul className="users">
    {users.map((user) => (
      <li key={user.id}>
        <User user={user} />
      </li>
    ))}
  </ul>
);

Using the curly braces as mentioned before, here we are mapping over a list of users, and rendering them one by one with their respective props on to the DOM. Notice the key attribute, React uses this to track what happened if you later reorder, delete, or add new items.

And that covers the use of state and components in React. Of course, things can and will get more complex, but it will be up to you how to handle them.

A couple of closing things:

Ecosystem

React does not cover everything you would need for more complex projects. There are a lot of great React tools and technologies out there that will help you during development. Here are some of them and a couple of scenarios where they would come in:

Sometimes, the built-in state management features of React might not suffice, particularly for complex applications. While state generally flows from parent to child components, there could be instances where you need to pass data from a child component back to a parent or even between sibling components. This is where state management libraries can come in handy. These libraries typically offer a 'global state,' often referred to as a 'store,' that is accessible from anywhere within your application. Some popular state management libraries include React Redux and Zustand.

An excellent tool for debugging and following the flow of data in your app is React Developer Tools.

If you are looking for a way to test your components in an isolated manner, cover performance, accessibility and create interactive documentation for the components you build for your app I would recommend Storybook.

While React itself is a powerful library with many options for configuration, there are frameworks available that come pre-configured and offer additional features. These frameworks can accelerate your development process and enhance your applications:

Next.js - A production-ready React framework that significantly extends React's capabilities. It offers features such as Routing, built-in CSS support, Server-side Rendering, and more.

Remix.js - Another React framework that, like Next.js, comes with a host of features that make it easier to build complex applications.

In the end, there are multiple tools at our disposal. It is up to us to choose what we need for our projects and what best fits our needs.

Community

Due to its popularity, React benefits from a very active community where you can find answers to questions, packages, libraries, articles, and much more.

Useful links

The official React documentation

If you want to learn more about class-based components click here

Community

I learned a lot from people on YouTube, here are some of them:

Jack Herrington

Brad Traversy

Free Code Camp

Ania Kubow

The Net Ninja

(not sponsored) I also have found a lot of great courses on frontendmasters.com.

Brian Holt

Steve Kinney

And many more, frontendmasters is a paid service platform for learning.

Final words

If this article was helpful and you have learned something from it, I hope you will feel confident in exploring and experimenting with React. Now go ahead and try building something cool!

Ready to Take Your Tech Project to the Next Level?

We’ve been there, navigating the complexities of modern tech stacks and finding solutions that deliver. If you’re looking to transform your project, you’re not alone.

Connect with us at 20robots. We’re experts in AI Integration and Digital Transformation. Let us help you make your next big tech leap.