React Course: Using Web Storage

When developing a web application, it is very important to store and manage user data on the client side.
In this course, we will learn how to utilize web storage in a React application.
Web storage is implemented through two main methods, namely session storage and local storage.

What is Web Storage?

Web storage provides a way to store data on the client side.
It is a simple API provided by the browser, allowing data to be stored and read without requesting the server.
There are two main types of web storage.

  • Local Storage: Data is persistently stored even when the user is using the web application. The data remains even if the browser session ends.
  • Session Storage: Data is only maintained during the session of the browser tab or window. Closing the tab or exiting the browser will make the data disappear.

Using Web Storage in React

Using web storage in React is very easy. Here, we will illustrate how to use local storage and session storage with a simple example.

1. Using Local Storage

Let’s create a simple component that saves and retrieves data using local storage.


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

const LocalStorageExample = () => {
    const [name, setName] = useState('');

    useEffect(() => {
        const storedName = localStorage.getItem('name');
        if (storedName) {
            setName(storedName);
        }
    }, []);

    const handleChange = (event) => {
        const newName = event.target.value;
        setName(newName);
        localStorage.setItem('name', newName);
    };

    return (
        

Local Storage Example

Stored Name: {name}

); }; export default LocalStorageExample;

In the code above, we receive the user’s name, store it in local storage, and retrieve the saved name when the page is reloaded.
We use the useEffect hook to read data from local storage when the component mounts.

2. Using Session Storage

Next, let’s create an example for saving and retrieving data using session storage.


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

const SessionStorageExample = () => {
    const [sessionData, setSessionData] = useState('');

    useEffect(() => {
        const storedData = sessionStorage.getItem('sessionData');
        if (storedData) {
            setSessionData(storedData);
        }
    }, []);

    const handleChange = (event) => {
        const newData = event.target.value;
        setSessionData(newData);
        sessionStorage.setItem('sessionData', newData);
    };

    return (
        

Session Storage Example

Stored Data: {sessionData}

); }; export default SessionStorageExample;

In this example using session storage, the user’s input data can be maintained during the browser session.
The data is automatically deleted when the session ends. Such functionality is useful in cases like shopping cart and temporary storage.

Web Storage API

When dealing with web storage, the following API is used:

  • setItem(key, value): Stores a value for a specified key.
  • getItem(key): Returns the value for a specified key. Returns null if the key does not exist.
  • removeItem(key): Deletes the value stored for a specified key.
  • clear(): Deletes all stored data.
  • key(index): Returns the key at the specified index.
  • length: Returns the number of stored items.

Advantages and Disadvantages of Web Storage

Let’s look at the advantages and disadvantages of using web storage.

Advantages

  • Easy to Use: Web storage is very easy to use. You can store and read data without complex setup.
  • No Asynchronous Handling Needed: Data can be stored and retrieved immediately without server requests.
  • Throughput: Data reading and writing performance is excellent.

Disadvantages

  • Storage Capacity Limit: Local storage is limited to about 5MB per domain.
  • Security Issues: Caution is needed when storing sensitive information. Data stored on the client side can be easily accessed, so privacy should be protected.
  • Browser Dependency: The behavior of web storage may vary depending on the browser used by the user.

Use Cases of Web Storage

Web storage can be useful in various situations. Here are some common use cases.

  • User Preference Settings: You can store user-selected themes or language settings to provide the same environment during the next login.
  • Shopping Cart Feature: In online shopping malls, items added to the cart can be stored in local storage to retain data until the user checks out.
  • Temporary Storage: You can save data to local storage from user input forms to avoid losing data even if the user leaves the page.

Conclusion

Web storage is a useful tool for storing and managing data on the client side in React applications.
Through this course, you have learned the basic usage of local storage and session storage and explored various use cases.
Try to utilize web storage in your future projects!

References

React Course: Web Storage

Overview

Web storage is a mechanism that allows web applications to store data on the user’s browser. It is mainly divided into two types: Local Storage and Session Storage. These two storages differ in terms of usage and lifespan of the data stored. By using web storage, you can implement faster and more efficient web applications. In this course, we will delve deep into how to use web storage with React.

Understanding Web Storage

1. What is Web Storage?

The Web Storage API is an API that allows web applications to store data on the client side. It provides a way to store data permanently in the browser. This API is divided into two main types:

  • Local Storage: Stores data permanently. The data remains even when the user closes the browser.
  • Session Storage: Stores data for one session only. The data disappears when the tab or browser is closed.

2. Reasons to Use Web Storage

  • Performance Improvement: Helps reduce server requests and increases data access speed.
  • Offline Support: Allows data to be stored and used even when the user is offline.
  • Improved User Experience: Provides a more personalized experience by storing user-customized data.

React and Web Storage

React is a powerful library for efficiently updating the UI through state management. By utilizing web storage, you can manage data in React applications more easily and intuitively. Below are methods to leverage web storage in React.

Setting Up a React Project

As the first step, you need to create a React project. You can create a new React application using create-react-app:

npx create-react-app web-storage-example
cd web-storage-example
npm start

Using the above commands, you can create and run a basic React application. Now you are ready to implement the web storage functionality.

Handling Web Storage API

1. Example of Using Local Storage

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

const LocalStorageExample = () => {
    const [value, setValue] = useState('');

    useEffect(() => {
        const storedValue = localStorage.getItem('myValue');
        if (storedValue) {
            setValue(storedValue);
        }
    }, []);

    const handleChange = (e) => {
        setValue(e.target.value);
        localStorage.setItem('myValue', e.target.value);
    };

    return (
        

Local Storage Example

Stored Value: {value}

); }; export default LocalStorageExample;

2. Example of Using Session Storage

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

const SessionStorageExample = () => {
    const [value, setValue] = useState('');

    useEffect(() => {
        const storedValue = sessionStorage.getItem('mySessionValue');
        if (storedValue) {
            setValue(storedValue);
        }
    }, []);

    const handleChange = (e) => {
        setValue(e.target.value);
        sessionStorage.setItem('mySessionValue', e.target.value);
    };

    return (
        

Session Storage Example

Stored Value: {value}

); }; export default SessionStorageExample;

Security of Web Storage

When using web storage, security should be a concern. Here are points to keep in mind:

  1. Do not store sensitive information: Sensitive data such as passwords and credit card information should never be stored in web storage.
  2. Prevent XSS attacks: Applications using web storage can be vulnerable to XSS attacks. To prevent this, input data validation should be thorough.

Integration Scenarios of React and Web Storage

Common scenarios for utilizing web storage in React include user settings, form data retention, and cached data management. Below are examples of these scenarios.

Saving User Settings

You can store the theme (dark mode, light mode, etc.) selected by the user in local storage to ensure that the previously selected theme remains even after refreshing the page.

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

const ThemeSwitcher = () => {
    const [theme, setTheme] = useState('light');

    useEffect(() => {
        const storedTheme = localStorage.getItem('theme');
        if (storedTheme) {
            setTheme(storedTheme);
        }
    }, []);

    const toggleTheme = () => {
        const newTheme = theme === 'light' ? 'dark' : 'light';
        setTheme(newTheme);
        localStorage.setItem('theme', newTheme);
    };

    return (
        

Theme Switcher

); }; export default ThemeSwitcher;

Retaining Form Data

It is possible to store the form data entered by the user in local storage so that the values persist even after refreshing the page.

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

const FormExample = () => {
    const [formData, setFormData] = useState({ name: '', email: '' });

    useEffect(() => {
        const storedData = JSON.parse(localStorage.getItem('formData'));
        if (storedData) {
            setFormData(storedData);
        }
    }, []);

    const handleChange = (e) => {
        const { name, value } = e.target;
        setFormData({ ...formData, [name]: value });
        localStorage.setItem('formData', JSON.stringify({ ...formData, [name]: value }));
    };

    return (
        

Form Example

Name: {formData.name}

Email: {formData.email}

); }; export default FormExample;

Conclusion

Web storage is an important tool for efficiently managing client-side data in React applications and improving user experience. Through Local Storage and Session Storage, you can greatly enhance the performance and convenience of web applications. However, it’s crucial to consider security and avoid storing sensitive data in web storage.

We hope that this course has helped you understand web storage and how to utilize it efficiently in React applications. While data storage is an easy and intuitive task, remember that approaching it the right way is the most important aspect.

React Course: Operators

React is a library for building efficient user interfaces. Today, we will study operators frequently used in React in depth. Operators are important tools in programming languages that create new values using two or more operands. In React, various operators can be used to dynamically update the UI and interact with the user.

1. Basic Operators in JavaScript

As React is written in JavaScript, it is important to understand the basic JavaScript operators. The operators in JavaScript can be categorized as follows:

1.1. Arithmetic Operators

Arithmetic operators are used to perform basic mathematical operations. The representative arithmetic operators are as follows:

  • Addition (+): Adds two values.
  • Subtraction (-): Subtracts the second value from the first value.
  • Multiplication (*): Multiplies two values.
  • Division (/): Divides the first value by the second value.
  • Modulus (%): Returns the remainder of the division of the first value by the second value.

For example:

const a = 10;
const b = 5;
const sum = a + b; // 15
const difference = a - b; // 5
const product = a * b; // 50
const quotient = a / b; // 2
const remainder = a % b; // 0

1.2. Comparison Operators

Comparison operators are used to compare two values and return a boolean value. Common comparison operators are as follows:

  • Equal (===): Returns true when both value and data type are the same.
  • Not Equal (!==): Returns true when either value or data type is different.
  • Greater Than (>): Returns true when the left value is greater than the right value.
  • Less Than (<): Returns true when the left value is less than the right value.
  • Greater Than or Equal (>=): Returns true when the left value is greater than or equal to the right value.
  • Less Than or Equal (<=): Returns true when the left value is less than or equal to the right value.

1.3. Logical Operators

Logical operators perform logical combinations of boolean values. The main logical operators are as follows:

  • AND (&&): Returns true when both conditions are true.
  • OR (||): Returns true when at least one of the two conditions is true.
  • NOT (!): Inverts a boolean value.

2. Using Operators in React

Operators can be used within React components to update the state and perform conditional rendering. Let’s look at some examples of how to use operators in React.

2.1. State Update

In React, state is an essential element for managing component data. You can manipulate values using arithmetic operators when updating the state.

import React, { useState } from 'react';

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

    const increment = () => {
        setCount(count + 1); // Using arithmetic operator
    };

    return (
        

Current count: {count}

); }

2.2. Conditional Rendering

In React, you can show components based on specific conditions through conditional rendering. You can easily implement conditional rendering using comparison operators and logical operators.

import React, { useState } from 'react';

function Greeting() {
    const [isLoggedIn, setIsLoggedIn] = useState(false);

    return (
        
{isLoggedIn ?

Welcome!

:

Login required.

}
); }

3. Advanced Operators

In addition to the basic operators mentioned above, React also allows for more complex logic through advanced operators. Here, we will look at some advanced operators.

3.1. Ternary Operator

The ternary operator is a way to express conditional rendering concisely. The format is as follows:

condition ? value if true : value if false

For example:

{isLoggedIn ? 

Welcome!

:

Login required.

}

3.2. Optional Chaining

Optional Chaining is a method to prevent errors when accessing deep properties of an object if that property does not exist. It can be used as shown in the code below:

const user = { name: 'John Doe', address: { city: 'Seoul' } };
const city = user.address?.city; // 'Seoul'
const country = user.address?.country; // undefined

4. Conclusion

In this lesson, we explored the concept and application of operators in React. You can dynamically update the state and construct various UIs through conditional rendering based on user interactions. To properly understand and utilize React, it is essential to firmly grasp the basic concepts of JavaScript operators.

We will continue to cover various topics related to React in the future. See you in the next lesson!

React Course: Spread Operator and Rest Parameters

React is a JavaScript library that is widely used for building user interfaces on the client side. By leveraging the advanced features of JavaScript, you can write more efficient and maintainable code. In this article, we will discuss the concepts of the spread operator (…) and rest parameters (…), and explain how to utilize these two in React components.

1. Spread Operator

The spread operator is used to expand all elements of an array or object individually. Introduced in ES6, this syntax improves code readability and enables easier data manipulation.

1.1 Spread Operator in Arrays

The spread operator can be used for copying, merging, or adding elements to arrays. Let’s look at the following example.

const arr1 = [1, 2, 3];
const arr2 = [4, 5, 6];

// Array Copy
const arrCopy = [...arr1];

// Array Merge
const combinedArr = [...arr1, ...arr2];

// Adding Elements to Array
const newArr = [...arr1, 0, ...arr2];

1.2 Spread Operator in Objects

The spread operator is similarly used for objects, allowing for copying, merging, and modifying objects.

const obj1 = { a: 1, b: 2 };
const obj2 = { c: 3, d: 4 };

// Object Copy
const objCopy = { ...obj1 };

// Object Merge
const combinedObj = { ...obj1, ...obj2 };

// Object Modification
const modifiedObj = { ...obj1, b: 5 };

2. Rest Parameters

Rest parameters are used in the function parameter list to bundle multiple arguments into an array. This is particularly useful when the number of parameters is not fixed.

2.1 Basic Usage of Rest Parameters

As shown in the example below, you can use rest parameters to handle multiple arguments as a single array.

function sum(...numbers) {
    return numbers.reduce((acc, curr) => acc + curr, 0);
}

console.log(sum(1, 2, 3, 4)); // 10

3. Using Spread Operator and Rest Parameters in React

In React, the spread operator and rest parameters are very useful for state management and handling component props.

3.1 Using Spread Operator with Component Props

The spread operator allows you to pass all props of an object at once. This reduces code duplication and enables efficient prop propagation.

const Button = ({ label, ...props }) => {
    return <button {...props}>{label}</button>;
};

const App = () => {
    return <Button label="Click Me" onClick={() => alert('Clicked!')} />;
};

3.2 Using Rest Parameters for State Management

You can utilize rest parameters in React’s state management. The following example shows how to apply rest parameters in state updates.

const [state, setState] = useState({ a: 1, b: 2 });

const updateState = (newValues) => {
    setState((prevState) => ({
        ...prevState,
        ...newValues,
    }));
};

// Usage Example
updateState({ b: 3 });

4. Conclusion

The spread operator and rest parameters are very useful tools in React and JavaScript as a whole. They help keep code concise, improve readability, and enable efficient data processing. By actively utilizing these tools in React development, you can write cleaner and more maintainable code.

5. Additional Resources

If you would like more details, please refer to the following resources:

React Course: Scope

Hello! In this lecture, we will delve deeply into Scope in React. React is one of the most popular libraries in modern web development, helping to build user interfaces through a component-based architecture. Scope is one of the important concepts in JavaScript that represents the validity range of variables. Therefore, understanding scope within React components is essential.

1. What is Scope?

Scope refers to the range in which variables, functions, and objects are valid within a program. In JavaScript, there are mainly two types of scope: Global Scope and Local Scope.

  • Global Scope is the range of variables that can be accessed from anywhere in the code. For example, variables defined at the top level of a script belong to the global scope.
  • Local Scope is the range of variables that can only be accessed within a specific function or block. These variables exist only when the function or block is executed.

2. Types of JavaScript Scope

2.1 Global Scope

Global scope refers to variables that can be accessed from anywhere within the script. For example:

var globalVar = "This is a global variable";

function showGlobalVar() {
    console.log(globalVar);
}
showGlobalVar(); // This is a global variable

2.2 Function Scope

Function scope means that variables declared within a function are only valid within that function. For example:

function myFunction() {
    var localVar = "This is a local variable";
    console.log(localVar);
}

myFunction(); // This is a local variable
console.log(localVar); // Uncaught ReferenceError: localVar is not defined

2.3 Block Scope

Block scope, introduced in ES6 (ECMAScript 2015), allows you to define variables that are only valid within a { } block. Declaring variables with let or const creates block scope:

if (true) {
    let blockVar = "This is a block variable";
    console.log(blockVar); // This is a block variable
}

console.log(blockVar); // Uncaught ReferenceError: blockVar is not defined

3. Managing Scope in React

When writing components in React, scope is particularly important. Each component manages its own state and can receive data from parent components through props. A clear understanding of React’s state and props is necessary to grasp the concept of scope.

3.1 State and Scope

The state of a React component stores the data at the time of rendering the component, and is mainly managed using the useState hook. State is a local variable that can only be accessed within the component. For example:

import React, { useState } from 'react';

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

    return (
        

Current count: {count}

); }

3.2 Props and Scope

Props are a way to pass data from a parent component to a child component. Props have a global form for the child component, referencing values defined in the parent component. You can access props in a component as follows:

function ChildComponent(props) {
    return 

{props.title}

; } function ParentComponent() { return ; }

4. Closure and Scope

A closure is a combination of a function and the lexical environment in which that function was declared. In JavaScript, functions remember the scope in which they were created. Thus, closures provide powerful functionality by leveraging scope.

function makeCounter() {
    let count = 0;
    return function() {
        count += 1;
        return count;
    };
}

const counter = makeCounter();
console.log(counter()); // 1
console.log(counter()); // 2

5. Conclusion

In this lecture, we learned about the concept of scope in React. Scope is a very important factor when defining and accessing variables, and without a basic understanding of JavaScript, writing components in React can be challenging. In future lectures, we will cover more advanced topics, so please look forward to it!