Arama Yap Mesaj Gönder
Biz Sizi Arayalım
+90
X
X
X
X

Knowledge Base

Homepage Knowledge Base General What is React JS? A Guide to Web De...

Bize Ulaşın

Konum Halkalı merkez mahallesi fatih cd ozgur apt no 46 , Küçükçekmece , İstanbul , 34303 , TR

What is React JS? A Guide to Web Development with React

React is an open-source JavaScript library developed by Facebook and used to create user interfaces (UI). It is ideal for creating single-page applications (SPAs) and managing dynamic content. Thanks to its component-based architecture, virtual DOM usage, and declarative programming approach, React enables developers to create high-performance, scalable, and easy-to-maintain web applications. In this comprehensive guide, we will examine every aspect of React, from the basics to advanced topics. You can take your projects even further by receiving Web Software Services.

1. Basics of React

1.1. What is React and Why Use It?

React is a JavaScript library and is specifically designed for creating user interfaces. Here are the main reasons to use React:

  • Component-Based Architecture: React makes it easy to break down applications into small, reusable components. This makes the code more organized and easier to maintain.
  • Virtual DOM: React improves performance by using a virtual DOM. The virtual DOM is a copy of the real DOM, and the real DOM is only updated when there are changes.
  • Declarative Programming: React uses a declarative approach to define user interfaces. This allows developers to specify what they want and let React determine how to do it.
  • Ease of Learning: React is easier to learn compared to other JavaScript frameworks.
  • Community Support: React has a large and active community. This helps developers solve their problems and learn new skills.

1.2. Basic Concepts of React

To understand React, it is important to know the following basic concepts:

  • Components: They are the basic building blocks of React applications. A component represents a part of the user interface and has its own data and behavior.
  • JSX: It is the abbreviation of JavaScript XML. It is used to define user interfaces using an HTML-like syntax in React components.
  • Props: Used to pass data to components. Props define the properties of components and determine how the components will behave.
  • State: It is the internal data of a component. State can change the behavior of the component over time.
  • Lifecycle Methods: These are the methods that run during the creation, updating, and removal of components.

1.3. Environment Setup and First React Application

To start React development, first make sure that Node.js and npm (Node Package Manager) or yarn are installed on your computer. Then, you can create a React application by following these steps:

    1. Creating a Project with Create React App: Create React App is an officially supported tool for creating React applications. You can create a new project by running the following command in the terminal:
npx create-react-app my-app
    1. Navigating to the Project Folder: After the project is created, navigate to the project folder:
cd my-app
    1. Starting the Application: To start the application, run the following command:
npm start
  1. This command will automatically open the application in your browser.

2. Components and JSX

2.1. Definition and Types of Components

There are two types of components in React:

  • Functional Components: These are JavaScript functions that take props and return JSX.
  • Class Components: These are ES6 classes and are derived from React.Component. They can use state and lifecycle methods.

Functional Component Example:


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

Class Component Example:


class Welcome extends React.Component {
  render() {
    return <h1>Hello, {this.props.name}!</h1>;
  }
}

2.2. JSX Syntax and Rules

JSX allows you to use HTML-like tags within JavaScript. Some basic rules of JSX are:

  • Single Root Element: A component must return a single root element. You can use a container element (e.g., <div>) to return multiple elements.
  • JavaScript Expressions: You can use curly braces ({}) to use JavaScript expressions within JSX.
  • HTML Attributes: When using HTML attributes, there are some differences. For example, you need to use "className" instead of "class" and "htmlFor" instead of "for".

JSX Example:


function App() {
  const name = 'React';
  return (
    <div className="container">
      <h1>Hello, {name}!</h1>
      <p>Web development with React.</p>
    </div>
  );
}

2.3. Props and State Management

Props are used to pass data to components, while state is a component's internal data. Props are used to pass data from the parent component to the child component, and the child component cannot modify the props. State, on the other hand, is a component's own internal data, and the component can modify the state.

Props Example:


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

function App() {
  return <Welcome name="React" />;
}

State Example:


import React, { useState } from 'react';

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

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

3. Lifecycle Methods

3.1. Lifecycle Methods in Class Components

In class components, there are lifecycle methods that run at different stages of the component's lifecycle. These methods are used to perform specific operations during the creation, updating, and removal of the component.

  • constructor(): The first method that runs when the component is created. It is used to initialize the state and bind event handlers.
  • render(): The method that returns the component's user interface.
  • componentDidMount(): The method that runs after the component is inserted into the DOM. It is used for data fetching or subscription operations.
  • componentDidUpdate(): The method that runs after the component is updated. It is used for DOM updates or side effects.
  • componentWillUnmount(): The method that runs before the component is removed from the DOM. It is used for cleanup operations (e.g., unsubscribing from subscriptions).

3.2. useEffect Hook in Functional Components

The useEffect hook is used in functional components to provide functionality similar to lifecycle methods. useEffect is used to perform specific operations during the creation, updating, and removal of the component.

useEffect Example:


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

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

  useEffect(() => {
    // Runs when the component mounts and when count changes
    document.title = `Counter: ${count}`;

    // Cleanup function (runs when the component unmounts)
    return () => {
      document.title = 'React Application';
    };
  }, [count]); // Dependency array (useEffect runs when count changes)

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

4. Event Handling and Forms

4.1. Event Handling in React

Event handling in React is similar to event handling in HTML, but there are some differences. React events use camelCase syntax (e.g., onClick instead of onclick). Also, React event handlers are used to update the state of components and change the user interface.

Event Handling Example:


import React, { useState } from 'react';

function Button() {
  const [text, setText] = useState('Click');

  const handleClick = () => {
    setText('Clicked!');
  };

  return (
    <button onClick={handleClick}>{text}</button>
  );
}

4.2. Controlled and Uncontrolled Form Components

In React, form components are divided into two types: controlled and uncontrolled:

  • Controlled Components: The value of form elements is managed by the state of the React component. This makes it easy to control and validate the value of form elements.
  • Uncontrolled Components: The value of form elements is managed by the DOM. This requires using ref to get the value of form elements.

Controlled Form Component Example:


import React, { useState } from 'react';

function NameForm() {
  const [name, setName] = useState('');

  const handleChange = (event) => {
    setName(event.target.value);
  };

  const handleSubmit = (event) => {
    event.preventDefault();
    alert(`Your name: ${name}`);
  };

  return (
    <form onSubmit={handleSubmit}>
      <label>
        Your name:
        <input type="text" value={name} onChange={handleChange} />
      </label>
      <button type="submit">Submit</button>
    </form>
  );
}

Uncontrolled Form Component Example:


import React, { useRef } from 'react';

function NameForm() {
  const inputRef = useRef(null);

  const handleSubmit = (event) => {
    event.preventDefault();
    alert(`Your name: ${inputRef.current.value}`);
  };

  return (
    <form onSubmit={handleSubmit}>
      <label>
        Your name:
        <input type="text" ref={inputRef} />
      </label>
      <button type="submit">Submit</button>
    </form>
  );
}

5. Style Management

5.1. Styling with CSS

You can use CSS to style React components. You can import CSS files directly into your components or use inline styles.

Importing CSS File:


import './MyComponent.css';

function MyComponent() {
  return <div className="my-component">Hello, React!</div>;
}

Inline Styles:


function MyComponent() {
  const style = {
    color: 'blue',
    fontSize: '20px'
  };

  return <div style={style}>Hello, React!</div>;
}

5.2. CSS-in-JS Solutions

CSS-in-JS is an approach that allows you to write CSS within JavaScript. This allows you to define the style of components directly within the component code. Popular CSS-in-JS solutions include:

  • Styled Components: A library used to define styles for React components.
  • Emotion: Another popular option for CSS-in-JS.
  • JSS: A library that allows you to write CSS with JavaScript.

Styled Components Example:


import styled from 'styled-components';

const StyledButton = styled.button`
  background-color: blue;
  color: white;
  font-size: 16px;
  padding: 10px 20px;
  border: none;
  border-radius: 5px;
`;

function MyComponent() {
  return <StyledButton>Click</StyledButton>;
}

6. Routing

6.1. Using React Router Dom

React Router Dom is a library used to manage routing operations in React applications. It is used to navigate between different pages in single-page applications (SPA).

Installation:

npm install react-router-dom

Usage Example:


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

function Home() {
  return <h2>Homepage</h2>;
}

function About() {
  return <h2>About Us</h2>;
}

function App() {
  return (
    <Router>
      <nav>
        <ul>
          <li>
            <Link to="/">Homepage</Link>
          </li>
          <li>
            <Link to="/about">About Us</Link>
          </li>
        </ul>
      </nav>

      <Routes>
        <Route path="/" element={<Home/>} />
        <Route path="/about" element={<About/>} />
      </Routes>
    </Router>
  );
}

6.2. Dynamic Routes and Parameters

React Router Dom allows you to navigate to different pages using dynamic routes and parameters. For example, in a product list application, you can create a different page for each product.

Dynamic Route Example:


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

function Product() {
  const { id } = useParams();
  return <h2>Product ID: {id}</h2>;
}

function App() {
  return (
    <Router>
      <nav>
        <ul>
          <li>
            <Link to="/product/1">Product 1</Link>
          </li>
          <li>
            <Link to="/product/2">Product 2</Link>
          </li>
        </ul>
      </nav>

      <Routes>
        <Route path="/product/:id" element={<Product/>} />
      </Routes>
    </Router>
  );
}

7. Data Management

7.1. Context API

Context API is a mechanism used to share data between components in React. In particular, it is used to avoid props drilling (passing props to child components).

Creating Context:


import React from 'react';

const MyContext = React.createContext();

export default MyContext;

Context Provider:


import React, { useState } from 'react';
import MyContext from './MyContext';

function App() {
  const [theme, setTheme] = useState('light');

  return (
    <MyContext.Provider value={{ theme, setTheme }}>
      <MyComponent/>
    </MyContext.Provider>
  );
}

Context Consumer:


import React, { useContext } from 'react';
import MyContext from './MyContext';

function MyComponent() {
  const { theme, setTheme } = useContext(MyContext);

  return (
    <div style={{ backgroundColor: theme === 'light' ? 'white' : 'black', color: theme === 'light' ? 'black' : 'white' }}>
      <p>Theme: {theme}</p>
      <button onClick={() => setTheme(theme === 'light' ? 'dark' : 'light')}>Change Theme</button>
    </div>
  );
}

7.2. Redux

Redux is a predictable state container for JavaScript apps. It is used to simplify state management, especially in large and complex applications.

Basic Concepts:

  • Store: The object that holds the application's state.
  • Actions: Objects used to change the state.
  • Reducers: Functions that update the state by processing actions.
  • Dispatch: The function used to send actions to reducers.
  • Subscribe: The function used to listen for changes in the store.

Redux Example:

    1. Redux Installation:
npm install redux react-redux
    1. Actions:

const INCREMENT = 'INCREMENT';

export const increment = () => ({
  type: INCREMENT
});
    1. Reducer:

const initialState = {
  count: 0
};

const reducer = (state = initialState, action) => {
  switch (action.type) {
    case INCREMENT:
      return {
        ...state,
        count: state.count + 1
      };
    default:
      return state;
  }
};

export default reducer;
    1. Store:

import { createStore } from 'redux';
import reducer from './reducer';

const store = createStore(reducer);

export default store;
    1. Component:

import React from 'react';
import { connect } from 'react-redux';
import { increment } from './actions';

function Counter(props) {
  return (
    <div>
      <p>Counter: {props.count}</p>
      <button onClick={props.increment}>Increment</button>
    </div>
  );
}

const mapStateToProps = (state) => ({
  count: state.count
});

const mapDispatchToProps = {
  increment
};

export default connect(mapStateToProps, mapDispatchToProps)(Counter);
    1. Provider:

import React from 'react';
import { Provider } from 'react-redux';
import store from './store';
import Counter from './Counter';

function App() {
  return (
    <Provider store={store}>
      <Counter/>
    </Provider>
  );
}

8. API Integration

8.1. Using Fetch API

Fetch API is an interface used to make HTTP requests in web browsers. It is used in React applications to fetch and send data from APIs.

Data Fetching Example:


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

function Users() {
  const [users, setUsers] = useState([]);

  useEffect(() => {
    fetch('https://jsonplaceholder.typicode.com/users')
      .then(response => response.json())
      .then(data => setUsers(data));
  }, []);

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

8.2. Axios Library

Axios is a Promise-based HTTP client for browsers and Node.js. It provides more features and convenience compared to Fetch API. For example, it offers features such as automatic JSON transformation, request cancellation, and error management.

Installation:

npm install axios

Data Fetching Example:


import React, { useState, useEffect } from 'react';
import axios from 'axios';

function Users() {
  const [users, setUsers] = useState([]);

  useEffect(() => {
    axios.get('https://jsonplaceholder.typicode.com/users')
      .then(response => setUsers(response.data));
  }, []);

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

9. Testing

9.1. Unit Tests

Unit tests are used to test the smallest parts of an application (e.g., functions, components) separately. Unit tests are important to verify that the code works correctly and does not have unexpected side effects.

Popular Testing Libraries:

  • Jest: A testing framework developed by Facebook. It is specifically designed for React applications.
  • Mocha: A flexible and extensible testing framework.
  • Chai: An assertion library. It is used to verify test results.

9.2. Integration Tests

Integration tests are used to test that different parts of the application (e.g., components, modules) work together correctly. Integration tests are important to verify the interaction of different parts, beyond unit tests.

9.3. End-to-End Tests

End-to-end tests are used to test that the entire application (user interface, backend, database) works together correctly. End-to-end tests are important to simulate user scenarios and verify how the application performs in real-world conditions.

10. Performance Optimization

10.1. Performance Analysis Tools

Various tools can be used to analyze the performance of React applications. These tools help identify performance issues and identify optimization opportunities.

  • React Profiler: It is a part of React development tools. It is used to analyze component render times and performance bottlenecks.
  • Chrome DevTools: These are the browser's development tools. It is used to analyze various metrics such as performance, memory, and network traffic.
  • Lighthouse: A tool used to analyze the performance, accessibility, SEO, and other metrics of web pages.

10.2. Memory Management

Memory management is an important factor affecting the performance of React applications. It is necessary to be careful to avoid unnecessary memory consumption and prevent memory leaks.

  • Preventing Unnecessary Renders: React.memo, useMemo, and useCallback hooks can be used to prevent components from rendering unnecessarily.
  • Managing Large Data Structures: Pagination, virtualization, and lazy loading techniques can be used to efficiently manage large data structures (e.g., arrays, objects).
  • Preventing Memory Leaks: Performing cleanup operations (e.g., canceling subscriptions, stopping timers) when components unmount helps prevent memory leaks.

11. Real-World Examples and Case Studies

11.1. E-commerce Application

In an e-commerce application, React can be used to create various components such as product listing, shopping cart management, payment processing, and user interface. React's component-based architecture ensures that the application is modular and easy to maintain.

11.2. Social Media Platform

In a social media platform, React can be used for various components such as user profiles, post feeds, notifications, and messaging.

Can't find the information you are looking for?

Create a Support Ticket
Did you find it useful?
(1034 times viewed / 418 people found it helpful)

Call now to get more detailed information about our products and services.

Top