← All writing

React Revisit

A React refresher covering components, state, rendering, effects, refs and reducers, with attention to closures and component lifecycles. Includes practical notes on requests, Markdown rendering, animation and deployment.

React Revisit

Create Project with Vite

sh
npm create vite@latest

Name your project and then install dependencies.

sh
npm install

Run project by

sh
npm run dev

Basic

main.jsx is the entry file.

react
import { StrictMode } from 'react'
import { createRoot } from 'react-dom/client'
import './index.css'
import App from './App.jsx'

createRoot(document.getElementById('root')).render(
  <StrictMode>
    <App />
  </StrictMode>
)

And we have a index.html, this will find the div which id = root and then add all components in this div.

html
<!doctype html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <link rel="icon" type="image/svg+xml" href="/vite.svg" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Vite + React</title>
  </head>
  <body>
    <div id="root">
        <!-- Add all components here -->
    </div>
    <script type="module" src="/src/main.jsx"></script>
  </body>
</html>

And App.jsx is our root component.

Component

A component in React is a reusable building block for your user interface (UI).

Functional Components : These are simple JavaScript functions that return JSX (which looks like HTML).

One function is one component.

react
import './App.css'

// Upper case for component
function App() {
    return (
        // lower case for html
        <h1>hello react!!</h1>
    )
}
export default App

Note: function name (used as component name) must be first letter Upper Case and funtion must be pure.

And html label must be lower case.

JSX

JSX is a syntax extension for JavaScript that lets you write HTML-like markup inside a JavaScript file.

JSX is a special way of writing JavaScript. That means it’s possible to use JavaScript inside it—with curly braces { }.

react
export default function TodoList() {
  const name = 'Gregorio Y. Zara';
  return (
    <h1>{name}'s To Do List</h1>
  );
}

Props

We use props to pass the parameters to child components.

react
//father
export default function father() {
  return (
    <Son
      person = {{ name: 'Lin Lanying', imageId: '1bX5QH6' }}
      size={100}
    />
  );
}

// syntactic suger
// Destructure props
function Son({ person, size = 100})  // default value is allowed
{ 
    print(person);
}

// Same as this
function Son(props) {
  let person = props.person;
  let size = props.size;
  // ...
}

Destructuring Object

You have a object

react
const person = {
  name: "Alice",
  age: 30,
  isStudent: false
};

Then we can use destructuring object to extract value and rename it.

react
const {
    name : newName
    age : newAge
    isStudent : newIsStudent
} = person

console.log(newName);

Key props

key props are used to identify unique component instance for diffing algorithm to work well

State

We can cosider state as the state in Automaton. (informally)

If a component has more than one state, we need use something(useState create this) to represent its current state.

react
import { useState } from 'react'
import './App.css'

function App() {

    const display = useState(0);

    return (
        <>
            <h1>hello react!!</h1>
            {display ? <h2>show</h2> : null}
        </>   
    )
}
export default App

Now App has two states, one will display <h2>show</h2> and the other will not.

So we use useState to create a variable display to represent its state.

display = 0 means current state is not showing, otherwise is showing.

useState will return a function which is setDisplay in this example.

It can be used to change current state.

So we use this to design our transition function of Automaton (informally)

react
function App() {

    const [display, setDisplay] = useState(0);

    function handleClick() {
        setDisplay(1 - display)
    }

    return (
        <>
            <h1 onClick={handleClick}>hello react!!</h1>
            {display ? <h2>show</h2> : null}
        </>   
    )
}

Update state based current state

react
    function handleClick() {
		// use a lambda function
        setDisplay((display) => !display)
    }

How does useState work?

Since our function or say component is pure function.

Whenever react found the state variable is changed by set function, then it will re-render this component again i.e., compute this funciton again!!

Math function perspective

So we can regard state as the funciton input, whenever it changes react need recalculate this function.

REACT

React is called "react" beacuse

React reacts to state changes by re-rendering the UI

Life Cycle

React update states batches not single. This means several updating can cause only one render and commit.

Render is triggered

  1. Initial render of the application.
  2. State is updated in one or more component instances (re-render)

Render phase

The Render Phase is pure calculation. React does the following:

1.Calls your function component(s)

2.Evaluates JSX → React elements: JSX is compiled into JavaScript objects (not HTML yet).

3.Builds a "virtual DOM" tree React compares the new tree to the previous one (diffing).

4.Prepares a list of updates (not applied yet)

Note: At this stage, no actual DOM operations or side effects happen.

Virtual DOM

This virtual DOM is just a JavaScript object that mirrors the structure of the actual DOM, but it is not directly rendered to the screen.

When a component’s state or props change, React updates the virtual DOM instead of immediately manipulating the real DOM. This allows React to perform changes without affecting the actual DOM directly.

Thue react can use diff algorithm to compare difference and do a minimal update.

Commit phase

The commit phase is where all the real work happens—React applies the changes to the DOM

Browser paint

Once browser notices that DOM is changed, it will re-paint to screen.

Effect

After browser painting, useEffect will run the effect function.

Side effect

Component instance life cycle

Mount / Initial render

Re-render

Unmount

useEffect

Absolutely — useEffect is one of the most important hooks in React. It lets you run side effects in your function components (like fetching data, interacting with the DOM, timers, etc.).

react
useEffect(function() {
    fetch(`http://www.omdbapi.com/?apikey=${KEY}&s=intersteller`)
        .then(res => res.json)
        .then(data => console.log(data.Search))
}, [dependency1, dependency2])

The first argument is function you want to run with side effect.

And second argument is dependency array.

It tell react only run this effect if one of these dependencies (dependency1, dependency2) has changed since the last render including mount.

Empty array = "no dependencies". React runs the effect only once, after the browser painting

If no second argument, react runs this effect after every render, always.

Thus, we can regard dependency array is a synchronization of effect and dependencies.

NOTE:

Effect runs after browser painting.

Clean up

Clean up phase takes place after component unmounted and before every rerender takes place.

Return a clean up function to run in clean up phase.

react
//change title
useEffect(function(){
    document.title = `Moive | ${title}`;

    //clean up function
    return function() {
        document.title = "usePopcorn";
    }
}, [title])

useRef

useRef is a React Hook that creates a mutable reference to a value that persists across renders without causing re-renders.

Commonly used to reference DOM elements, store instance values, or track mutable state that doesn’t need to trigger UI updates

react
// press enter key to focus search input.
function Search({movieQuery, setMovieQuery}) {
    const inputEl = useRef(null);
    useEffect(() => {
        function callback(e) {
            if (Document.activeElement === inputEl.current)
                return; // If the input is already focused, do nothing
            
            if (e.key === "Enter") {
                console.log("Enter key pressed, focusing input element");
                // Focus the input element when the component mounts
                // inputEl.current is exact dom element.
                inputEl.current.focus();
            }
        }
        // Add event listener to focus the input element when the component mounts
        document.addEventListener("keydown", callback);

        return () => {
            // Clean up the event listener when the component unmounts
            document.removeEventListener("keydown", callback);
        };
    }, []);

    return (
        // Whenever input value is change, call setMoiveQuery
        // and change movieQuery to echo 
        <input
            ref={inputEl}
            className="search" 
            type = "text" 
            value = {movieQuery}
            onChange={(e)=>{setMovieQuery(e.target.value)}}
        >
        </input>
    )
}

Custom hook

A custom hook in React is a reusable function that uses one or more built-in React hooks (like useState, useEffect, useRef, etc.) to encapsulate common logic.

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

function useFetch(url) {
  const [data, setData] = useState(null);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    const controller = new AbortController();
    fetch(url, { signal: controller.signal })
      .then((res) => res.json())
      .then((json) => {
        setData(json);
        setLoading(false);
      })
      .catch((err) => {
        if (err.name !== 'AbortError') {
          console.error(err);
        }
      });

    return () => controller.abort(); // Cleanup on unmount
  }, [url]);

  return { data, loading };
}

export default useFetch;

use

react
import useFetch from './hooks/useFetch';

function Users() {
  const { data, loading } = useFetch('https://api.example.com/users');

  if (loading) return <p>Loading...</p>;
  return (
    <ul>
      {data.map((user) => (
        <li key={user.id}>{user.name}</li>
      ))}
    </ul>
  );
}

useReducer

useReducer is a React hook used for managing complex state logic, especially when:

  • The next state depends on the previous state
  • You have multiple related state values
  • You want a cleaner alternative to useState with if/else or switch logic
react
const [state, dispatch] = useReducer(reducer, initialState);

  • reducer: A function that receives state and action, and returns the new state
  • dispatch: A function to send actions
  • initialState: The initial state value
react


import { useReducer } from 'react';

function reducer(state, action) {
  switch (action.type) {
    case 'increment':
      return { count: state.count + 1 };
    case 'decrement':
      return { count: state.count - 1 };
    default:
      return state;
  }
}


function Counter() {
  const [state, dispatch] = useReducer(reducer, { count: 0 });
  return (
    <div>
      <p>Count: {state.count}</p>
      <button onClick={() => dispatch({ type: 'decrement' })}>-</button>
      <button onClick={() => dispatch({ type: 'increment' })}>+</button>
    </div>
  );
}

Promise

Asynchronous code allows things to happen in the background while the rest of your program keeps running.

A Promise is an object that represents a future value — something that hasn't finished yet, but will later.

async / await

More details async.

async and await are syntax sugar over Promises. They let you write asynchronous code that looks like synchronous code.

js
(async()=>{
    // async let your function execute asynchronously.
    // But there must be await or Promise 
    async function RunBackground() {
        await new Promise(resolve => setTimeout(resolve, 1000)); // true async
        return 42;
    }
    
    // const res = await RunBackground();
    const res = RunBackground()
    console.log("Saber~")
    console.log("Saber~~")
    console.log("Saber~~")
    console.log(res)
})();

Saber~... will output first since RunBackground is asynchronous.

And async will let the return value of function become a promise.

Code
// result without await
Saber~
Saber~~
Saber~~
Promise { <pending> }       
Done

Thus await waits asynchronous function until the promise is resolved (i.e., corresponding asynchronous function finished).

Code
// result with await
Done
Saber~
Saber~~
Saber~~
42

fetch

fetch is a async function and return a promise

Style

Inline

Use a JS object

react
const containerStyle = {
    display : "flex",
    alignItems : "center",
    gap : "16px"
}
function StarRating() {
    return (
        <div style = {containerStyle}>
        </div>
    )
}

CSS file

react
import './index.css'

function App() {

    return (
        // need to remove the prefix '.'
        <div className = "main"></div>
    )
}

Event handlers

react
function example {
    function handler() {
        ...
    }
    return (
    	<div onClick = {handler}>
        <div>
    )
}

NOTE: This only works on original html NOT component

Component will regard this as its props.

Closure

react
import { useState } from "react"

function StarRating({maxRating = 5}) {
    const [rating, setRating] = useState(0)
    function handleRating(rating) {
        setRating(rating)
    }

    return (
        <div style = {starContainerStyle}>
            {Array(maxRating).fill(0).map((_, i)=> 
            // Closure
            <Star key={i} onRate = {()=>handleRating(i + 1)} />)}
        </div>
    )
}

function Star({onRate}) {
    return (
        <span style ={starStyle} onClick={onRate}>
        </span>
    )
}

When click <span> in Star, onRate function has the memory of what the value of i is!

Events

onClick

onMouseEnter

When cursor hover, this event will be activated.

onMouseLeave

onChange

used in <input/>.

Common Usage

Controlled element

react
function Search() {
    const [searchMovieInput, setSearchMovieInput] = useState("")
    
    return (
        // Whenever input value is change, call setSearchMovieInput
        // and change to searchMovieInput to echo 
        <input className="search" type = "text" value = {searchMovieInput}
            onChange={(e)=>{setSearchMovieInput(e.target.value)}}
        >
        </input>
    )
}

Conditional rendering

react
function Box({children}) {

    // Use it to control displaying
    const [isOpen, setIsOpen] = useState(true);

    // click button to show or hide children component
    return (
        <div className="box">
            <button onClick={()=>setIsOpen(open => !open)}>
                {isOpen ? '-' : '+'}
            </button>
            {isOpen && children}
        </div>
    )
}

When tempRating is true, then render tempRating .

If tempRating is false, then if rating is true, render rating .

Otherwise render "".

react
<p style = {textStyle}>{tempRating || rating || ""}</p>

Render List

Use map and lambda expression (functional program)

react
function MovieList() {
	movies = ["saber", "saber", "saber"]
    return (
        <ul className="list list-movies">
          {movies.map((movie) => (
                <h1>movie</h1>
          ))}
        </ul>
    );
}

Create a array and then map it

react
function StarRating() {
    return (
        <div>
            <div>
                {Array(5).fill(0).map((_, i)=> <span>S {i + 1}</span>)}
            </div>
            <p></p>
        </div>
    )
}

Marked.js

See more https://marked.js.org/using_advanced

js
import { marked } from 'marked';
marked.parse(markdownString ,[options])

markdownString:String of markdown source to be compiled.

options, some options. Can also use marked.use to set global options

js
// Set options
marked.use({
  async: true,
  break: true
  gfm: true,
});

marked-hightlight

We can also new a marked object by Marked. This is marked-hightlight extension.

react
import { Marked } from "marked";
import { markedHighlight } from "marked-highlight";
import hljs from 'highlight.js';

const marked = new Marked(
    markedHighlight({
      emptyLangClass: 'hljs',
      langPrefix: 'hljs language-',
      highlight(code, lang, info) {
        const language = hljs.getLanguage(lang) ? lang : 'plaintext';
        return hljs.highlight(code, { language }).value;
      }
    })
  );

marked-katex-extension

react
const katexOptions = {
    throwOnError: false,
    nonStandard: true,
    displayMode: false
}

const markedOptions = {
    breaks : true,
    gfm: true
}

marked.use(markedKatex(katexOptions))

react
    const handleFileUpload = async (e) => {
        const file = e.target.files[0];
        if (!file) return;
        const text = await file.text();
        const html = marked.parse(text);
        setRenderedMarkdown(html);
    };

Axios

Response is already JSON parsed (res.data), however in fetch you must call res.json().

react
import axios from 'axios';

NOTE: res.data is the true data.

GET

react
async function getArticles()
{
    const res = await axios.get(url, {
        params: {
            page: 1,
            pageSize: 5
        }
    })
    setArticles(res.data)
}

POST

js
const res = await axios.post("http://localhost:8080/admin/upload", formData, {
            headers: {
              "Content-Type": "multipart/form-data",
            },
          });

// res.data is the true data

Code
async function handleClick() {
    try {
        const response = await axios.post(url, {name, description});
      } catch (error) {
        console.error('GET error:', error);
      }
}

GSAP

Deployment

Place .env files in the root directory of your React project

File NameUsed When You Run...Purpose
.envAlwaysCommon defaults
.env.developmentnpm startLocal development overrides
.env.productionnpm run buildProduction build settings
.env.stagingCustom build setups (optional)Staging/test environment

Write some variables.

Code
VITE_API_BASE_URL=http://localhost:8080

Then load it in src/config/config.js.

js
const config = {
  apiBaseUrl: import.meta.env.VITE_API_BASE_URL,
};

export default config;

Use config as an object.

jsx
import config from '../config/api';

fetch(`${config.apiBaseUrl}/posts`);

← Back to ArchiveBack to top ↑

Comments

No approved comments yet.

Your display name and plain-text comment become public only after owner approval. No account or email is required.