Richard Qiu

Full Stack

2 notes

Contents

React

Important Features of React:

  • Virtual DOM: React uses a virtual DOM to efficiently update and render components, ensuring fast performance by minimizing direct DOM manipulations. When changes occur, React updates only the necessary parts of the real DOM, instead of re-rendering everything.
  • Component-Based Architecture: React builds UI using reusable, isolated components, making code more modular, maintainable, and scalable.
  • Hooks: React Hooks allow functional components to manage state and side effects, making them powerful and more flexible.
  • Server-Side Rendering (SSR): React can be used for server-side rendering, where HTML content is generated on the server and sent to the client. This improves the app’s performance, especially for SEO.
  • React Router: React Router enables navigation in a React application. It allows you to define different routes for different views in a single-page application (SPA).

Props and State

image-20250626033813389

React allows us to pass information to a Component using something called props (which stands for properties). Props are objects which can be used inside a component

We can access any props inside from the component’s class to which the props is passed. The props can be accessed as shown below:

this.props.propName;

Virtual DOM

image-20250626025238126

Real DOM and virtual DOM difference

image-20250626025318274

JSX

JSX is basically a syntax extension of regular JavaScript and is used to create React elements. These elements are then rendered to the React DOM. All the React components are written in JSX. To embed any JavaScript expression in a piece of code written in JSX we will have to wrap that expression in curly braces {}.

React Components

image-20250626025547609

✅ Functional Component (with Hooks)

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

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

  useEffect(() => {
    console.log('Component mounted or updated');
  }, [count]); // Only runs when `count` changes

  return (
    <div>
      <p>You clicked {count} times</p>
      <button onClick={() => setCount(count + 1)}>
        Click me
      </button>
    </div>
  );
}

export default Counter;

🧱 React Class Component = OOP Class

import React, { Component } from 'react';

class Counter extends Component {
  constructor(props) {
    super(props);              // Calls the parent (Component) constructor
    this.state = { count: 0 }; // Initializes local state
  }

  componentDidUpdate() {
    console.log('Component updated');
  }

  render() {
    return (
      <div>
        <p>You clicked {this.state.count} times</p>
        <button onClick={() => this.setState({ count: this.state.count + 1 })}>
          Click me
        </button>
      </div>
    );
  }
}

shouldComponentUpdate() - class

In React, lifecycle methods provide hooks into different phases of a component’s lifecycle, enabling developers to control its behaviour at various stages. One such lifecycle method is shouldComponentUpdate().

It plays an important role in optimizing component rendering and ensuring that unnecessary updates are avoided, improving the performance of React applications.

The shouldComponentUpdate() is a lifecycle method used in React class components to determine whether a component should re-render in response to changes in state or props. This method is invoked before every render and allows you to conditionally skip the re-rendering process, which can help optimize performance by preventing unnecessary updates.

  • If shouldComponentUpdate() returns true, the component re-renders.
  • If it returns false, the component does not re-render.
import React, { Component } from "react";

class Counter extends Component {
    constructor() {
        super();
        this.state = {
            count: 0,
        };
    }

    shouldComponentUpdate(nextProps, nextState) {
        if (nextState.count === this.state.count) {
            return false;
        }
        return true;
    }

    increment = () => {
        this.setState({ count: this.state.count + 1 });
    };

    render() {
        console.log("Counter component re-rendered");
        return (
            <div style={{ textAlign: "center" }}>
                <p>Count: {this.state.count}</p>
                <button onClick={this.increment}>Increment</button>
            </div>
        );
    }
}

export default Counter;
  • The Counter component has a shouldComponentUpdate() method that checks if the count state has changed.
  • If the count is the same as before, the component does not re-render, saving resources.
  • Only when the count changes will the component re-render.

Difference

image-20250626030514909

React render

React renders HTML to the web page by using a function called render(). The purpose of the function is to display the specified HTML code inside the specified HTML element. In the render() method, we can read props and state and return our JSX code to the root component of our app.

ReactJS Keys

A key serves as a unique identifier in React, helping to track which items in a list have changed, been updated, or removed. It is particularly useful when dynamically creating components or when users modify the list.

const numbers = [1, 2, 3, 4, 5];
const updatedNums = numbers.map((number, index) =>
    <li key={index}>
        {number}
    </li>
);

Data Binding

Data binding is a technique that binds data sources from the provider and consumer together and synchronizes them. In other words, Data Binding means sharing data between components to view and view to component.

  • Data binding in React can be achieved by using a controlled input.
  • A controlled input is achieved by binding the value to a state variable and an onChange event to change the state as the input value changes.

1 way data binding

import React, { useState } from 'react';

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

    return (
        <div>
            <h1>Count: {count}</h1>
            <button onClick={() => setCount(count + 1)}>Incre</button>
        </div>
    );
}

export default comp;

2 ways data binding

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

function App() {
    const [subject, setSubject] = useState("");

    const handleInputChange = (event) => {
        setSubject(event.target.value);
    };

    return (
        <div className="container">
            <h1>Two-Way Data Binding Example</h1>
            <div className="content">
                <input
                    type="text"
                    placeholder="Enter a subject..."
                    value={subject}
                    onChange={handleInputChange}  // Update state on change
                    className="input-field"
                />
                <p>Your selected subject is: <b>{subject || "___"}</b></p>
            </div>
        </div>
    );
}

export default App;

useContext

useContext is a React Hook that allows functional components to consume values from a context, without writing deeply nested props (props drilling).

In large apps, passing data (like theme, user, language) down multiple component levels via props becomes messy. Context provides a centralized way to share data across the component tree.

1. Create Context

import React, { createContext } from 'react';

export const ThemeContext = createContext('light');

2. Provide Context Value

import React from 'react';
import { ThemeContext } from './ThemeContext';
import App from './App';

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

3. Consume Context using useContext

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

function App() {
  const theme = useContext(ThemeContext);
  return <div>The current theme is {theme}</div>;
}

Summary Table

Feature Description
createContext Creates a Context object
Provider Supplies the context value
useContext Hook to access context inside components

Best Practices

  • Keep context only for global/shared state (e.g., theme, user, auth).
  • Avoid putting frequently changing state (like mouse position) in context — it causes many re-renders.

nginx

Systemd(system demon)

Systemd is a service management tool in linux that can be used to create a new service.

Create Http Flask service

After configure the reverse proxy successful in nginx, we can deploy the python flask application by using gunicorn(https://gunicorn.org/#quickstart) to deploy. Gunicorn ‘Green Unicorn’ is a Python WSGI HTTP Server for UNIX.

[Why should I use gunicorn to deploy instead of using python?](###Why should I use gunicorn to deploy instead of using python?)

Create a [name].service file under /etc/systemd/system/

Example service file for my gunicron application

[Unit]
Description=Gunicorn instance to serve flask_testing
After=network.target

[Service]
User=ubuntu
Group=ubuntu
WorkingDirectory=/home/ubuntu/flask_testing
Environment="PATH=/home/ubuntu/flask_testing/flasktestvenv/bin"
ExecStart=/home/ubuntu/flask_testing/flasktestvenv/bin/gunicorn --workers 2 --bind 0.0.0.0:5000 app:app

[Install]
WantedBy=multi-user.target

Useful cmd:

sudo systemctl daemon-reload	//Reload the systemd manager configuration to make it aware of the new service file:
sudo systemctl enable gunicorn	//Enable the service to start on boot:
sudo systemctl start gunicorn	//Start the service:
sudo systemctl status gunicorn	//Verify that the service is running without errors:

sudo systemctl restart gunicorn
sudo systemctl stop gunicorn
journalctl -u gunicorn

Resources

HTTPS & SSL

How to auto generate the SSL certificate and set up the ssl in Nginx to make the website use https

I find it really easy to configure the SSL by using the certbot by following the below link. I am using AWS EC2 ubuntu instance.

https://certbot.eff.org/instructions?ws=nginx&os=ubuntufocal

The only change I need to make is

NGINX CMD

sudo nginx -t Check the nginx syntax verfication

sudo systemctl reload nginx

sudo systemctl restart nginx

Reference

Why should I use gunicorn to deploy instead of using python?

  1. Production-Ready: The Flask built-in server is intended for development purposes only. It is not optimized for production use and does not provide the necessary features for handling production traffic efficiently and securely. Gunicorn, on the other hand, is designed for production use and can handle multiple requests concurrently.
  2. Concurrency: Gunicorn can manage multiple worker processes. This allows it to handle many requests at the same time, improving the responsiveness and performance of your application. The built-in Flask server is single-threaded and can only handle one request at a time, making it unsuitable for high-traffic applications.
  3. Load Balancing: Gunicorn can spawn multiple worker processes, which can be distributed across multiple CPU cores. This makes better use of the server’s resources and improves performance. The built-in Flask server does not support multiple workers or load balancing.
  4. Graceful Handling of Connections: Gunicorn provides graceful handling of connections and worker processes, ensuring that requests are completed even if a worker process is restarted or shut down. This helps maintain uptime and provides a better experience for users.
  5. Security: Gunicorn is more secure for production use as it is designed to handle various security concerns such as handling untrusted client data. The built-in Flask server lacks these production-level security features.
  6. Compatibility with WSGI Servers: Gunicorn is a WSGI (Web Server Gateway Interface) HTTP server for Python web applications. It allows your Flask application to be served by any WSGI-compatible web server, providing flexibility and scalability. The built-in Flask server does not support WSGI, limiting its compatibility with other web servers.
  7. Integration with Reverse Proxies: Gunicorn works well with reverse proxies like Nginx. Nginx can handle static files, SSL termination, and can act as a load balancer, forwarding requests to Gunicorn. This setup enhances performance and security while providing more robust server management.
  8. Reliability and Robustness: Gunicorn has been battle-tested in production environments and is known for its reliability and robustness. It handles edge cases and failures gracefully, ensuring your application remains available.

In summary, while the built-in Flask server is great for development and testing, Gunicorn provides the necessary features, performance, and security required for deploying a Flask application in a production environment.

← All notes