React JS – basics

React JS is a JavaScript library created by Facebook (now Meta) for building user interfaces, particularly in Single Page Applications (SPA). Its popularity stems from its high performance, flexibility, and ability to easily create dynamic, interactive web pages.

Why use React JS?

React focuses on building components that can be reused in various parts of an application. Its virtual DOM approach allows for efficient management of user interface updates, significantly improving performance compared to traditional DOM manipulation methods.

Additionally, React JS has gained immense popularity due to its simplicity, large community, and support for building both web and mobile applications (via React Native). Many companies around the world use React in their projects, making it a valuable technology for any front-end developer.

Basic concepts in React JS

Components

The basic building block of a React application is a component. These are self-contained, isolated pieces of the interface that can be reused in different parts of the application. There are two main types of components:

Functional components – based on JavaScript functions.

Class components – use ES6 classes and were previously a popular choice. However, after the introduction of hooks in React 16.8, functional components have become the preferred method.

Example of a functional component:

function Welcome() {
  return <h1>Welcome to React!</h1>;
}

JSX (JavaScript XML)

JSX is a JavaScript syntax extension that allows mixing JavaScript logic with HTML code. Instead of writing HTML in separate files, JSX enables placing it directly in JavaScript functions. This makes code management easier and increases readability.

JSX example:

const element = <h1>Hello, World!</h1>;

JSX is transformed into standard JavaScript calls under the hood, which allows for efficient DOM manipulation.

Props

Props are a way to pass data between components. They are immutable, meaning that a parent component passes data to a child component, but the child cannot modify them.

Example:

function User(props) {
  return <h1>Welcome, {props.name}!</h1>;
}

<User name="John" />

Here, the User component receives the value of props.name and displays “Welcome, John!”.

State

State refers to dynamic data that can change during the application’s lifecycle. In functional components, we use the useState hook to manage state.

Example:

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

  return (
    <div>
      <p>Counter: {count}</p>
      <button onClick={() => setCount(count + 1)}>Increase</button>
    </div>
  );
}

In this case, the state (count) changes with each button click.

Component Lifecycle

Class component lifecycle

Class components have well-defined lifecycle stages, such as:

Mounting – when the component is added to the DOM (e.g., componentDidMount).

Updating – when the component is updated (e.g., componentDidUpdate).

Unmounting – when the component is removed from the DOM (e.g., componentWillUnmount).

Hooks in functional components

With the introduction of hooks, functional components can manage side effects using hooks like useEffect.

Example:

useEffect(() => {
  document.title = `Click count: ${count}`;
}, [count]);

Events and event handling in React

React has a built-in mechanism for handling events such as mouse clicks or text field value changes.

Example of handling a click event:

function Button() {
  function handleClick() {
    alert('Button clicked!');
  }

  return <button onClick={handleClick}>Click me</button>;
}

We can also pass functions as props to allow parent components to control interactions in child components.

Routing in React – React Router

Most applications require navigation between different pages. React Router is a popular library for handling routing in React.

To set up routing, first, install the react-router-dom package, and then define the routes in your application.

Example configuration:

import { BrowserRouter as Router, Route, Link } from 'react-router-dom';

function App() {
  return (
    <Router>
      <div>
        <Link to="/">Home</Link>
        <Link to="/about">About</Link>

        <Route exact path="/" component={Home} />
        <Route path="/about" component={About} />
      </div>
    </Router>
  );
}

Working with Forms in React

Controlled Components

In controlled forms, field values are stored in the component’s state.

Example:

function LoginForm() {
  const [email, setEmail] = useState('');

  return (
    <form>
      <input value={email} onChange={(e) => setEmail(e.target.value)} />
    </form>
  );
}

Uncontrolled Components

In uncontrolled forms, data is retrieved directly from the DOM using references.

Examples:

function LoginForm() {
  const emailRef = useRef();

  return (
    <form>
      <input ref={emailRef} />
    </form>
  );
}

Styling in React

React offers several approaches to styling components. You can use traditional CSS stylesheets or more modern tools like Styled Components.

Example:

import styled from 'styled-components';

const Button = styled.button`
  background-color: blue;
  color: white;
`;

<Button>Click me</Button>

State Management Basics in React

useState vs useReducer

useState is the simplest hook for managing state, while useReducer offers more control in more complex cases.

Context API

The Context API allows sharing global data without the need to pass props through multiple component levels.

Example:

const ThemeContext = React.createContext();

function App() {
  return (
    <ThemeContext.Provider value="dark">
      <Toolbar />
    </ThemeContext.Provider>
  );
}

Connecting to an API with React

React makes it easy to fetch data from external APIs using fetch or Axios.

useEffect(() => {
  fetch('https://api.example.com/data')
    .then(response => response.json())
    .then(data => setData(data));
}, []);

Conclusion

You’ve learned the basics of React, such as components, state, props, and the component lifecycle. The next step could be learning advanced tools like Redux or building more complex applications using external APIs and the Context API. React is a powerful tool that will undoubtedly boost your productivity as a front-end developer.

let's create something together