<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>Forem: Ayako yk</title>
    <description>The latest articles on Forem by Ayako yk (@ayako_yk).</description>
    <link>https://forem.com/ayako_yk</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F723297%2Fa907ae63-7246-44ea-83d4-58a8ee5233b2.png</url>
      <title>Forem: Ayako yk</title>
      <link>https://forem.com/ayako_yk</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://forem.com/feed/ayako_yk"/>
    <language>en</language>
    <item>
      <title>Exploring PL/SQL Collection Methods: DELETE, TRIM, and Their Best Practices</title>
      <dc:creator>Ayako yk</dc:creator>
      <pubDate>Sun, 30 Nov 2025 03:21:39 +0000</pubDate>
      <link>https://forem.com/ayako_yk/exploring-plsql-collection-methods-delete-trim-and-their-best-practices-3630</link>
      <guid>https://forem.com/ayako_yk/exploring-plsql-collection-methods-delete-trim-and-their-best-practices-3630</guid>
      <description>&lt;p&gt;In my previous blog post, I covered the fundamentals of PL/SQL collections, focusing on the different types: Associative Arrays, Nested Tables, and VARRAYs. While there’s much more to explore about collections, in this post, I’ll focus on two important collection methods: DELETE and TRIM.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Collection Methods&lt;/strong&gt;&lt;br&gt;
PL/SQL provides a variety of functions and procedures known as collection methods.&lt;/p&gt;

&lt;p&gt;They are called methods because they use member method syntax, unlike functions or procedures, which require passing collections as parameters. The syntax is similar to other programming languages, such as JavaScript.&lt;/p&gt;

&lt;p&gt;For example:&lt;br&gt;
&lt;code&gt;COUNT&lt;/code&gt; function: Returns the current number of elements in a collection.&lt;/p&gt;

&lt;p&gt;Wrong Syntax&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;COUNT(book_table)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Correct syntax&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;book_table.COUNT
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Note that collection methods are available only in PL/SQL, not within SQL.&lt;/p&gt;

&lt;p&gt;While I’m not listing and explaining all the collection methods, let’s focus on DELETE and TRIM, as they have interesting behaviors we should know.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;DELETE Method&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;DELETE 
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;em&gt;(without any arguments)&lt;/em&gt;&lt;br&gt;
Deletes all the rows from the collection.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;DELETE(i)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Removes the i-th element from a nested table or associative array.&lt;br&gt;
(Note: VARRAYs do not allow deleting specific elements.)&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;DELTE(i, j)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Removes all elements in an inclusive range starting from &lt;em&gt;i&lt;/em&gt; and ending at &lt;em&gt;j&lt;/em&gt;.&lt;/p&gt;

&lt;p&gt;Important Note: When you use parameters with DELETE, a placeholder is kept for the “removed” element.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;TRIM Method&lt;/strong&gt;&lt;br&gt;
TRIM removes n elements from the end of a nested table or VARRAY. Using TRIM with an associative array will raise an error. Without arguments, TRIM pops one element from the end of an array.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Do Not Use DELETE and TRIM on the Same Collection&lt;/strong&gt;&lt;br&gt;
If you use DELETE on an element at the end of a collection and then use TRIM on the same collection, it might seem like you’ve removed two elements. However, as mentioned earlier, the DELETE method places a placeholder for the removed element, so it only actually removes one element. Oracle recommends avoiding the use of both methods on the same collection.&lt;/p&gt;

&lt;p&gt;PL/SQL offers powerful and useful methods, but it’s important to pay close attention to how each one is used.&lt;/p&gt;

</description>
      <category>beginners</category>
      <category>learning</category>
      <category>database</category>
      <category>sql</category>
    </item>
    <item>
      <title>Understanding PL/SQL Collections: Associative Arrays, Nested Tables, and VARRAYs</title>
      <dc:creator>Ayako yk</dc:creator>
      <pubDate>Sun, 23 Nov 2025 03:03:09 +0000</pubDate>
      <link>https://forem.com/ayako_yk/understanding-plsql-collections-associative-arrays-nested-tables-and-varrays-3bmp</link>
      <guid>https://forem.com/ayako_yk/understanding-plsql-collections-associative-arrays-nested-tables-and-varrays-3bmp</guid>
      <description>&lt;p&gt;In the last blog post, I discussed a record, which is a composite data type. In this blog, I’ll talk about another composite data type: a collection.&lt;/p&gt;

&lt;p&gt;According to Oracle documentation, “&lt;em&gt;A collection is an ordered group of data elements, all of the same type&lt;/em&gt;.” A collection is a data structure similar to a list or array in other programming languages.&lt;/p&gt;

&lt;p&gt;PL/SQL supports three types of collections: Associative arrays, Nested tables, and Varrays.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Associative Arrays&lt;/strong&gt; &lt;br&gt;
These were called index-by tables in Oracle8 and Oracle8i databases. Associative arrays use arbitrary numbers or strings to look up elements, much like hash tables. They are *single-dimensional, *unbounded, and sparse collections. Associative arrays are available only in PL/SQL.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Nested Tables&lt;/strong&gt;&lt;br&gt;
Nested tables are also single-dimensional, unbounded collections of elements. They must be initially bounded but are allowed to be sparse, such as through deletion. Nested tables can be stored in database tables and manipulated through SQL.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;VARRAYs&lt;/strong&gt;&lt;br&gt;
VARRAYs (variable-sized arrays) are single-dimensional, but they are always bounded and never sparse. VARRAYs can be used both in PL/SQL and in a database.&lt;/p&gt;

&lt;p&gt;*single-dimensional: A PL/SQL collection always has just a single column of information in each row.&lt;/p&gt;

&lt;p&gt;*bounded and unbounded: A collection is bounded if it has predetermined limits for the number of rows. An unbounded collection has no upper or lower row limits.&lt;/p&gt;

&lt;p&gt;Let’s take a closer look at each type.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Associative Arrays&lt;/strong&gt;&lt;br&gt;
Syntax (to define a collection type):&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;TYPE type_name IS TABLE OF element_type [NOT NULL]

    INDEX BY [BINARY_INTEGER | PLS_INTEGER | VARCHAR2(size_limit)];

    INDEX BY key_type;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The &lt;code&gt;key_type&lt;/code&gt; can be either numeric or string. As they were previously called index-by tables, elements can be looked up by key-value pairs, which can save code and time because they don’t require loops. However, associative arrays are intended to be used only for temporary storage. To make an associative array persistent throughout the life of a database session, declare it in a package specification and populate it in the package body.  Note that associative arrays cannot be used with SQL operations, such as &lt;code&gt;INSERT&lt;/code&gt; or &lt;code&gt;SELECT INTO&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Nested Tables&lt;/strong&gt;&lt;br&gt;
Syntax (to define a collection type):&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;TYPE type_name IS TABLE OF element_type [NOT NULL];
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Here, &lt;code&gt;type_name&lt;/code&gt; is a type specifier used later to declare collections.&lt;/p&gt;

&lt;p&gt;To store nested tables in database tables, you must declare SQL types.&lt;br&gt;
Syntax (for SQL):&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;CREATE TYPE type_name IS TABLE OF element_type;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;VARRAYs&lt;/strong&gt;&lt;br&gt;
Syntax:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;TYPE type_name IS {VARRAY | VARYING ARRAY} (size_limit)

    OF element_type [NOT NULL];
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Where &lt;code&gt;type_name&lt;/code&gt; is a type specifier used later to declare collections, and &lt;code&gt;size_limit&lt;/code&gt; must be specified to indicate the maximum size.&lt;/p&gt;

&lt;p&gt;To store VARRAYs in database tables, you must declare SQL types.&lt;br&gt;
Syntax (for SQL):&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;CREATE TYPE type_name IS TABLE OF element_type;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Collection Constructors&lt;/strong&gt;&lt;br&gt;
A collection constructor is a system-defined function with the same name as a collection type.&lt;/p&gt;

&lt;p&gt;When a collection has no elements during initialization, it is considered an empty collection. However, a null collection does not exist, so it must be initialized --- either as empty or with non-NULL values.&lt;/p&gt;

&lt;p&gt;Syntax:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;collection_type([value [, value] ... ])
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;If the parameter list is empty, the constructor returns an empty collection. Otherwise, the constructor returns a collection containing the specified values.&lt;/p&gt;

&lt;p&gt;Example (from a documentation):&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;TYPE Foursome IS VARRAY(4) OF VARCHAR2(15);
team Foursome := Foursome();
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;VARRAYs and Nested Tables must be initialized; otherwise, they are null collections.&lt;br&gt;
Associative arrays are considered empty, not null, until populated.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;When to Use Which Type&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Associative Arrays:&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;When you need a relatively small lookup table.&lt;/li&gt;
&lt;li&gt;When passing collections to and from the database server.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Varrays:&lt;/strong&gt; &lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;When you know the maximum number of elements.&lt;/li&gt;
&lt;li&gt;When you usually access the elements sequentially.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Nested Tables:&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;When the number of elements is not fixed.&lt;/li&gt;
&lt;li&gt;When the index values are not consecutive.&lt;/li&gt;
&lt;li&gt;When you need to delete or update some elements, but not all elements simultaneously.&lt;/li&gt;
&lt;li&gt;When you would create a separate lookup table with multiple entries for each row of the main table, and access it through join queries.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;The Difference Between a Collection and a Record&lt;/strong&gt;&lt;br&gt;
In a collection, the internal components, called elements, are always the same data type:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;variable_name(index)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In a record, the internal components, called fields, can have different data types.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;variable
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;These are the fundamentals of collections. I’ll dive deeper into collections and share more details in the next blog post.&lt;/p&gt;

</description>
      <category>beginners</category>
      <category>database</category>
      <category>learning</category>
      <category>sql</category>
    </item>
    <item>
      <title>Understanding Records in PL/SQL: Benefits and Limitations</title>
      <dc:creator>Ayako yk</dc:creator>
      <pubDate>Sat, 01 Nov 2025 08:05:06 +0000</pubDate>
      <link>https://forem.com/ayako_yk/understanding-records-in-plsql-benefits-and-limitations-3jkp</link>
      <guid>https://forem.com/ayako_yk/understanding-records-in-plsql-benefits-and-limitations-3jkp</guid>
      <description>&lt;p&gt;In the past blog post, I discussed scalar data types (&lt;a href="https://dev.to/ayako_yk/an-introduction-to-commonly-used-plsql-data-types-598c"&gt;An Introduction to Commonly Used PL/SQL Data Types&lt;/a&gt;). In this blog post, I’ll move on to composite data types, with a focus on records.&lt;/p&gt;

&lt;p&gt;Here’s a quick review:&lt;br&gt;
&lt;strong&gt;Scalar data types&lt;/strong&gt; store single values without internal components. They represent one value, such as a number, string, or date. &lt;br&gt;
&lt;strong&gt;Composite data types&lt;/strong&gt; can store multiple values, such as records and collections.&lt;/p&gt;

&lt;p&gt;A record is a composite data structure, meaning it is made up of multiple related elements or components. According to &lt;a href="https://docs.oracle.com/cd/B13789_01/appdev.101/b10807/05_colls.htm#i20716" rel="noopener noreferrer"&gt;the Oracle documentation&lt;/a&gt;, &lt;em&gt;a record is a group of related data items stored in fields, where each field corresponds to a table column&lt;/em&gt;.&lt;/p&gt;

&lt;p&gt;The &lt;code&gt;%ROWTYPE&lt;/code&gt; attribute lets you declare a record that represents a row in a database table. This makes your code more flexible — even if the table structure changes (for example, if new columns are added), your record declaration remains valid.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Defining and Declaring Records&lt;/strong&gt;&lt;br&gt;
Here’s an example from the documentation:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;DECLARE
-- Declare a record type with 3 fields.
  TYPE rec1_t IS RECORD (field1 VARCHAR2(16), field2 NUMBER, field3 DATE);
-- For any fields declared NOT NULL, we must supply a default value.
  TYPE rec2_t IS RECORD (id INTEGER NOT NULL := -1, name VARCHAR2(64) NOT NULL := '[anonymous]');

-- Declare record variables of the types declared above.
  rec1 rec1_t;
  rec2 rec2_t;

-- Declare a record variable that can hold a row from the EMPLOYEES table.
-- The fields of the record automatically match the names and types of the columns.
-- Don't need a TYPE declaration in this case.
  rec3 employees%ROWTYPE;

-- Or we can mix fields that are table columns with user-defined fields.
  TYPE rec4_t IS RECORD (first_name employees.first_name%TYPE, last_name employees.last_name%TYPE, rating NUMBER);
  rec4 rec4_t;

BEGIN
-- Read and write fields using dot notation
  rec1.field1 := 'Yesterday';
  rec1.field2 := 65;
  rec1.field3 := TRUNC(SYSDATE-1);

-- We didn't fill in the NAME field, so it takes the default value declared above.
  dbms_output.put_line(rec2.name);
END;
/
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;There are actually three ways to declare a record in PL/SQL.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Table-Based Record&lt;/strong&gt;&lt;br&gt;
You can create a record based on an existing table by using the &lt;code&gt;%ROWTYPE&lt;/code&gt; attribute. Each field in the record automatically corresponds to a column in that table.&lt;/p&gt;

&lt;p&gt;Example:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;CREATE TABLE employees (
    emp_id          INTEGER,
    emp_name        VARCHAR2(200),
    emp_department  VARCHAR2(200)
);

DECLARE
    employees_rec    employees%ROWTYPE;
BEGIN
    ...
END;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Cursor-Based Record&lt;/strong&gt;&lt;br&gt;
First of all, a cursor is like a pointer to a result set (the rows returned by a query).&lt;/p&gt;

&lt;p&gt;You can declare a record based on a cursor using the &lt;code&gt;%ROWTYPE&lt;/code&gt; attribute, where each field corresponds to the columns in the cursor’s SELECT statement.&lt;/p&gt;

&lt;p&gt;Example:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;DECLARE
    CURSOR employees_cur IS
        SELECT * 
        FROM employees
        WHERE emp_department = 'marketing';

    emp_in_marketing_rec employees_cur%ROWTYPE;
BEGIN
    ...
END;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Programmer-Defined Record&lt;/strong&gt;&lt;br&gt;
If you don’t need a record that exactly matches a table or cursor, you can define your own custom record type using &lt;code&gt;TYPE...RECORD&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;Example:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;DECLARE
    TYPE employees_rectype IS RECORD (
        emp_id        employees.emp_id%TYPE,
        emp_name      employees.emp_name%TYPE,
        emp_address   VARCHAR2(200)
    );

    employees_info_rec employees_rectype;
BEGIN
    ...
END;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Operations on Records&lt;/strong&gt;&lt;br&gt;
Working with records instead of individual fields allows you to write cleaner and more concise code.&lt;/p&gt;

&lt;p&gt;Here are some operations that are currently supported by PL/SQL.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Record-Level Operations&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Copying: Contents can be copied from one record to another.&lt;/li&gt;
&lt;li&gt;NULL Assignment: A NULL value can be assigned to a record.&lt;/li&gt;
&lt;li&gt;Passing Records: A record can be defined and passed as an argument to procedures or functions.&lt;/li&gt;
&lt;li&gt;Returning Records: A record can be returned from a function.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;However, some limitations exist. For example, the &lt;code&gt;IS NULL&lt;/code&gt; condition does not work on entire records. You need to check each field individually to determine if it contains a &lt;code&gt;NULL&lt;/code&gt; value.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Field-Level Operations&lt;/strong&gt;&lt;br&gt;
When accessing a field within a record (either to read or update its value), you must use dot notation.&lt;/p&gt;

&lt;p&gt;Syntax&lt;br&gt;
&lt;em&gt;record_name.field_name&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;If you are referencing a record from a package, you can include the package name before the record name:&lt;/p&gt;

&lt;p&gt;&lt;em&gt;package_name.record_name.field_name&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;Records offer significant advantages by allowing us to work with related data more concisely and efficiently, rather than handling individual fields. However, it’s important to keep their limitations in mind and use them carefully, leveraging the available methods to achieve optimal results.&lt;/p&gt;

</description>
      <category>beginners</category>
      <category>database</category>
      <category>learning</category>
      <category>sql</category>
    </item>
    <item>
      <title>Understanding Oracle Datetime Datatypes: DATE, TIMESTAMP, and INTERVAL</title>
      <dc:creator>Ayako yk</dc:creator>
      <pubDate>Sun, 26 Oct 2025 08:23:58 +0000</pubDate>
      <link>https://forem.com/ayako_yk/understanding-oracle-datetime-datatypes-date-timestamp-and-interval-27al</link>
      <guid>https://forem.com/ayako_yk/understanding-oracle-datetime-datatypes-date-timestamp-and-interval-27al</guid>
      <description>&lt;p&gt;In this blog post, I’ll explore some fundamental concepts of Oracle’s datetime datatypes---specifically, the &lt;code&gt;DATE&lt;/code&gt;, &lt;code&gt;TIMESTAMP&lt;/code&gt;, and &lt;code&gt;INTERVAL&lt;/code&gt; datatypes. Time-based data is at the core of many applications, from tracking transactions to logging events, so understanding how Oracle handles dates and times is crucial for managing and manipulating this kind of information effectively.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;DATE and TIMESTAMP&lt;/strong&gt;&lt;br&gt;
Oracle used to have only one datatype for date and time, which was &lt;code&gt;DATE&lt;/code&gt;. Starting with Oracle 9i, three new &lt;code&gt;TIMESTAMP&lt;/code&gt; datatypes were introduced.&lt;/p&gt;

&lt;p&gt;The four datetime datatypes:&lt;br&gt;
&lt;code&gt;DATE&lt;/code&gt;&lt;br&gt;
&lt;code&gt;TIMESTAMP&lt;/code&gt;&lt;br&gt;
&lt;code&gt;TIMESTAMP WITH TIME ZONE&lt;/code&gt;&lt;br&gt;
&lt;code&gt;TIMESTAMP WITH LOCAL TIME ZONE&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;DATE&lt;/strong&gt;&lt;br&gt;
The &lt;code&gt;DATE&lt;/code&gt; datatype stores a date and time, resolved to the second. It does not include time zone information. For each &lt;code&gt;DATE&lt;/code&gt; value, Oracle stores century, year, month, date, hour, minute, and second.&lt;/p&gt;

&lt;p&gt;You can specify a &lt;code&gt;DATE&lt;/code&gt; value by:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Specifying the date value as a literal.&lt;/li&gt;
&lt;li&gt;Converting a character or numeric value to a date value with the &lt;code&gt;TO_DATE&lt;/code&gt; function.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Examples:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;-- Literal (’YYYY-MM-DD’):
DATE ‘1995-10-31’

-- Oracle date values:
TO_DATE(’1995-OCT-31 15:30’, ‘YYYY-MON-DD HH24:MI’, ‘NLS_DATE_LANGUAGE=AMERICAN’)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;TIMESTAMP&lt;/strong&gt;&lt;br&gt;
The &lt;code&gt;TIMESTAMP&lt;/code&gt; datatype is an extension of the &lt;code&gt;DATE&lt;/code&gt; datatype. It stores year, month, date, hour, minute, and second values. Additionally, it stores fractional seconds, which the &lt;code&gt;DATE&lt;/code&gt; datatype does not.&lt;br&gt;
The &lt;code&gt;TIMESTAMP&lt;/code&gt; datatype does not store time zone information.&lt;/p&gt;

&lt;p&gt;_TIMESTAMP [(fractional_seconds_precision)] _&lt;/p&gt;

&lt;p&gt;Where &lt;code&gt;fractional_seconds_precision&lt;/code&gt; is optional and specifies the number of digits (0 to 9). The default is 6.&lt;/p&gt;

&lt;p&gt;Example&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;--TIMESTAMP literal (TIMESTAMP ‘YYYY-MM-DD HH24:MI:SS.FF’):
TIMESTAMP ‘1995-10-31 12:34:56.78’
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;TIMESTAMP WITH TIME ZONE&lt;/strong&gt;&lt;br&gt;
The &lt;code&gt;TIMESTAMP WITH TIME ZONE&lt;/code&gt; datatype stores the time zone along with each date and time value. This makes it possible to manage date and time values in different time zones.&lt;/p&gt;

&lt;p&gt;The time zone offset represents the difference between local time and UTC (Coordinated Universal Time).&lt;/p&gt;

&lt;p&gt;&lt;em&gt;TIMESTAMP [(fractional_seconds_precision)] WITH TIME ZONE&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;Where &lt;code&gt;fractional_seconds_precision&lt;/code&gt; is optional and specifies the number of decimal places for seconds.&lt;/p&gt;

&lt;p&gt;Example:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;TIMESTAMP ‘1995-10-31 12:34:56.78 +03:00’
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;TIMEZONE WITH LOCAL TIME ZONE&lt;/strong&gt;&lt;br&gt;
The &lt;code&gt;TIMEZONE WITH LOCAL TIME ZONE&lt;/code&gt; datatype stores a date and time that is assumed to be in the local time zone. The data is normalized to the database’s time zone (the time zone of the server).&lt;/p&gt;

&lt;p&gt;&lt;em&gt;TIMESTAMP [(fractional_seconds_precision)] WITH LOCAL TIME ZONE&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;Where &lt;code&gt;fractional_seconds_precision&lt;/code&gt; is optional and specifies the number of decimal places for seconds.&lt;/p&gt;

&lt;p&gt;The difference between &lt;code&gt;TIMESTAMP WITH TIME ZONE&lt;/code&gt; and &lt;code&gt;TIMEZONE WITH LOCAL TIME ZONE&lt;/code&gt; can be explained in this example:&lt;/p&gt;

&lt;p&gt;Let’s say we have an employee clock-in application. The company is based in Tokyo, the employee works in Tokyo, and the database server is also in Tokyo. The employee then goes on a business trip to New York and clocks in from there. &lt;/p&gt;

&lt;p&gt;With &lt;code&gt;TIMESTAMP WITH TIME ZONE&lt;/code&gt;, the clock-in time is stored in New York time (Eastern Time). &lt;/p&gt;

&lt;p&gt;With &lt;code&gt;TIMEZONE WITH LOCAL TIME ZONE&lt;/code&gt;, the clock-in time is always stored in Tokyo (Japan) time, regardless of the employee’s actual location.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Interval Datatypes&lt;/strong&gt;&lt;br&gt;
Oracle9i introduced Interval datatypes, which are used to record and compute quantities of time.&lt;/p&gt;

&lt;p&gt;&lt;code&gt;DATE&lt;/code&gt; and all &lt;code&gt;TIMESTAMP&lt;/code&gt; datatypes represent instances of time (a specific point in time). &lt;code&gt;INTERVAL&lt;/code&gt; datatypes, on the other hand, refer to a specific amount or duration of time.&lt;/p&gt;

&lt;p&gt;There are two interval datatypes:&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;INTERVAL YEAR TO MONTH&lt;/strong&gt;&lt;br&gt;
The &lt;code&gt;INTERVAL YEAR TO MONTH&lt;/code&gt; datatype stores a period of time in terms of years and months.&lt;/p&gt;

&lt;p&gt;&lt;em&gt;INTERVAL YEAR [(year_precision)] TO MONTH&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;Where year_precision specifies the number of digits in the &lt;code&gt;YEAR&lt;/code&gt; field (from 0 to 9). The default is 2.&lt;/p&gt;

&lt;p&gt;You can specify interval values with literals.&lt;/p&gt;

&lt;p&gt;Example:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;INTERVAL ‘12-3’ YEAR(2) TO MONTH
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This specifies an interval of 12 years and 3 months.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;INTERVAL DAY TO SECOND&lt;/strong&gt;&lt;br&gt;
The &lt;code&gt;INTERVAL DAY TO SECOND&lt;/code&gt; datatype stores a period of time in days, hours, minutes, and seconds.&lt;/p&gt;

&lt;p&gt;&lt;em&gt;INTERVAL DAY [(day_precision)] TO SECOND [(fractional_seconds_precision)]&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;&lt;code&gt;day_precision&lt;/code&gt; specifies the number of digits in the &lt;code&gt;DAY&lt;/code&gt; field. Accepted values are 0 to 9, with a default of 2. &lt;/p&gt;

&lt;p&gt;&lt;code&gt;fractional_seconds_precision&lt;/code&gt; specifies the number of digits in the fractional part of seconds. Accepted values are 0 to 9, with a default of 6.&lt;/p&gt;

&lt;p&gt;Example:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;INTERVAL ‘2 3:45:10.666’ DAY TO SECOND(3)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This specifies an interval of 2 days, 3 hours, 45 minutes, 10 seconds, and 666 thousandths of a second.&lt;/p&gt;

&lt;p&gt;In short, Oracle’s &lt;code&gt;DATE&lt;/code&gt; and &lt;code&gt;TIMESTAMP&lt;/code&gt; datatypes store and manipulate time-related data, while the &lt;code&gt;INTERVAL&lt;/code&gt; datatypes handle periods of time. However, this is just the beginning. In future blog posts, I’ll explore more about these datatypes and their uses.&lt;/p&gt;

</description>
      <category>beginners</category>
      <category>database</category>
      <category>learning</category>
      <category>sql</category>
    </item>
    <item>
      <title>PL/SQL Program Data: Naming, Declaring, and Best Practices</title>
      <dc:creator>Ayako yk</dc:creator>
      <pubDate>Sat, 18 Oct 2025 12:40:25 +0000</pubDate>
      <link>https://forem.com/ayako_yk/plsql-program-data-naming-declaring-and-best-practices-jc2</link>
      <guid>https://forem.com/ayako_yk/plsql-program-data-naming-declaring-and-best-practices-jc2</guid>
      <description>&lt;p&gt;When handling data in programming, we need variables or constants to store and manipulate it. In PL/SQL, variables, constants, scalar types, composite types, and containerized types are collectively referred to as program data.&lt;/p&gt;

&lt;p&gt;Program data in PL/SQL is defined within a block and exists only for the duration of the PL/SQL session; it is not stored in the database. When working with program data, it’s important to declare its data structure clearly.&lt;/p&gt;

&lt;p&gt;In this blog, I’ll discuss the fundamentals of program data and some best practices for managing it in PL/SQL.&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Naming Program Data&lt;/li&gt;
&lt;li&gt;Double Quotes in Naming&lt;/li&gt;
&lt;li&gt;Naming Conventions&lt;/li&gt;
&lt;li&gt;Declaring Program Data&lt;/li&gt;
&lt;li&gt;Anchored Declarations&lt;/li&gt;
&lt;li&gt;Programmer-Defined Subtypes&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;&lt;strong&gt;Naming Program Data&lt;/strong&gt;&lt;br&gt;
When naming program data, there are a few rules and recommendations:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Length: Names can be up to 30 characters long.&lt;/li&gt;
&lt;li&gt;First Character: Names must start with a letter.&lt;/li&gt;
&lt;li&gt;Subsequent Characters: After the first letter, names can contain letters, numerals, $, #, and _.&lt;/li&gt;
&lt;li&gt;Case Sensitivity: All names are case-insensitive.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Double Quotes in Naming&lt;/strong&gt;&lt;br&gt;
One interesting thing about PL/SQL’s naming rules is that when using double quotes, all the rules, except the 30-character limit, become flexible.&lt;/p&gt;

&lt;p&gt;For example, these names are considered acceptable:&lt;br&gt;
&lt;code&gt;“123@”&lt;/code&gt;&lt;br&gt;
&lt;code&gt;“   ”&lt;/code&gt;(three spaces)&lt;/p&gt;

&lt;p&gt;However, double quotes should generally be avoided for naming program data. They are usually used for table names with lowercase extensions. Using double quotes in variable or constant names can make the code harder to read and maintain.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Naming Conventions&lt;/strong&gt;&lt;br&gt;
Using prefixes or suffixes can improve the readability and understanding of your variables. Here are some commonly used conventions:&lt;/p&gt;

&lt;p&gt;&lt;code&gt;l_&lt;/code&gt; for local variables&lt;br&gt;
&lt;code&gt;g_&lt;/code&gt; for global variables&lt;br&gt;
&lt;code&gt;_rt&lt;/code&gt; for record types&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Declaring Program Data&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Declaring Variables&lt;/strong&gt;&lt;br&gt;
To declare a variable in PL/SQL, use the following structure:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;_name_ _datatype_ [NOT NULL] [_default_assignment_];
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;em&gt;[ ] is optional&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;&lt;em&gt;name&lt;/em&gt;: The variable name, following the rules mentioned above.&lt;br&gt;
&lt;em&gt;datatype&lt;/em&gt;: Specifies the datatype for the variable, which allocates memory for it. &lt;br&gt;
&lt;code&gt;NOT NULL&lt;/code&gt;: If this is used, an exception will be raised if NULL is assigned to the variable.&lt;br&gt;
&lt;em&gt;default_assignment&lt;/em&gt;: Optionally assign a default value either by using an assignment operator (&lt;code&gt;:=&lt;/code&gt;) or the &lt;code&gt;DEFAULT&lt;/code&gt; keyword:&lt;/p&gt;

&lt;p&gt;Example&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;name VARCHAR2(10) := ‘John';
-- or
namd VARCHAR2(10) DEFAULT ‘John';
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Declaring Constants&lt;/strong&gt;&lt;br&gt;
To declare a constant, use the following syntax:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;name CONSTANT datatype [NOT NULL] := | DEFAULT default_value;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;code&gt;CONSTANT&lt;/code&gt;: The keyword indicating that the variable cannot be reassigned once it’s set.&lt;/p&gt;

&lt;p&gt;Constants should be initialized with a value during declaration. They cannot be changed after that.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Anchored Declarations&lt;/strong&gt;&lt;br&gt;
In PL/SQL, variables can be declared using types that are “anchored” to other sources, such as table columns or other PL/SQL variables. This is done using anchored declarations.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Scalar Anchoring (%TYPE)&lt;/strong&gt;&lt;br&gt;
You can anchor a variable to a column or another PL/SQL variable’s type using the &lt;code&gt;%TYPE&lt;/code&gt; attribute:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;variable_name attribute%TYPE [default_value];
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Here, &lt;code&gt;attribute&lt;/code&gt; can be a column in a database table or a scalar variable in PL/SQL.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Record Anchoring (%ROWTYPE)&lt;/strong&gt;&lt;br&gt;
You can also anchor a variable to a table row using &lt;code&gt;%ROWTYPE&lt;/code&gt;:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;variable_name table_name | cursor_name%ROWTYPE [default_value];
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In this case, the variable will inherit the structure of a row from the specified table.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Advantages of Anchored Declarations&lt;/strong&gt;&lt;br&gt;
Hardcoding the datatype when declaring a variable can lead to issues if the data structure changes over time. For example, if you initially declare a variable as &lt;code&gt;NUMBER(5, 2)&lt;/code&gt; and later the data grows to $1,000,000, the variable will not work correctly anymore.&lt;/p&gt;

&lt;p&gt;By using &lt;code&gt;%TYPE&lt;/code&gt;, PL/SQL can automatically adjust to changes in the underlying data type without breaking your code.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;NOT NULL with Anchoring&lt;/strong&gt;&lt;br&gt;
When declaring a variable using &lt;code&gt;%TYPE&lt;/code&gt;, you should ensure it is initialized with a default value.&lt;/p&gt;

&lt;p&gt;However, if the source of the &lt;code&gt;%TYPE&lt;/code&gt; is a database column that already has a &lt;code&gt;NOT NULL&lt;/code&gt; constraint, you do not need to specify a default value because the database already guarantees that a value will exist.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Programmer-Defined Subtypes&lt;/strong&gt;&lt;br&gt;
PL/SQL allows you to create your own subtypes or aliases based on predefined datatypes using the &lt;code&gt;SUBTYPE&lt;/code&gt; keyword.&lt;/p&gt;

&lt;p&gt;Example&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;SUBTYPE long_string IS VARCHAR2(10000);
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;There are two types of subtypes:&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Constrained Subtype&lt;/strong&gt;&lt;br&gt;
A constrained subtype applies specific restrictions to the base type, such as value ranges.&lt;/p&gt;

&lt;p&gt;Example&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;SUBTYPE age_limit IS NUMBER(3) RANGE 0 TO 150;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This restricts the value of &lt;code&gt;age_limit&lt;/code&gt; to a number between 0 and 150.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Unconstrained Subtype&lt;/strong&gt;&lt;br&gt;
An unconstrained subtype does not impose any restrictions on the base type. It is typically used when you simply want to give a more meaningful name to an existing datatype. &lt;/p&gt;

&lt;p&gt;Example&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;SUBTYPE long_string IS VARCHAR2(10000);
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In summary, handling program data in PL/SQL requires understanding how to declare variables, constants, and subtypes, and how to use naming conventions and anchored declarations effectively. By following these best practices, we can write more maintainable PL/SQL code.&lt;/p&gt;

</description>
      <category>beginners</category>
      <category>learning</category>
      <category>database</category>
      <category>sql</category>
    </item>
    <item>
      <title>An Introduction to Commonly Used PL/SQL Data Types</title>
      <dc:creator>Ayako yk</dc:creator>
      <pubDate>Sat, 11 Oct 2025 09:05:21 +0000</pubDate>
      <link>https://forem.com/ayako_yk/an-introduction-to-commonly-used-plsql-data-types-598c</link>
      <guid>https://forem.com/ayako_yk/an-introduction-to-commonly-used-plsql-data-types-598c</guid>
      <description>&lt;p&gt;PL/SQL has two primary categories of data types: Scalar data types and Composite data types. &lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Scalar data types store single values without internal components. They represent a single value like a number, string, or date. &lt;/li&gt;
&lt;li&gt;Composite data types store multiple values, such as records and collections.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Today, I will only discuss Scalar data types.&lt;/p&gt;

&lt;p&gt;PL/SQL is an extension of SQL, and many SQL features, including data types, can be used in PL/SQL. However, there are PL/SQL-specific data types as well. It is important to be cautious when using these types, especially when working with database tables, as certain data types in PL/SQL execution blocks may not be directly interpretable in the context of a table (or may need to be handled differently).&lt;/p&gt;

&lt;p&gt;Since there are so many data types in both SQL and PL/SQL, including subtypes of scalar data types, deprecated types, and those only maintained for backward compatibility, I will focus on the most commonly used data types as a starting point for beginners like myself.&lt;/p&gt;

&lt;p&gt;Scalar data types can be divided into four families, which store numbers, characters, boolean values, and date/time values.&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;&lt;p&gt;Number Types&lt;br&gt;
&lt;code&gt;NUMBER&lt;/code&gt;&lt;br&gt;
&lt;code&gt;PLS_INTEGER&lt;/code&gt;&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Character Types&lt;br&gt;
&lt;code&gt;CHAR&lt;/code&gt;&lt;br&gt;
&lt;code&gt;VARCHAR2&lt;/code&gt;&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Boolean Type&lt;br&gt;
&lt;code&gt;BOOLEAN&lt;/code&gt;&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Datetime Types&lt;br&gt;
&lt;code&gt;DATE&lt;/code&gt;&lt;/p&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;&lt;strong&gt;Number Types&lt;/strong&gt;&lt;br&gt;
Number types allow us to store numeric data.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;NUMBER&lt;/strong&gt;&lt;br&gt;
The NUMBER data type stores fixed-point or floating-point numbers. It has a range from 1E-130 to 10E125. You can specify two attributes for the NUMBER type:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt; Precision:  The total number of digits (both to the left and right of the decimal point).&lt;/li&gt;
&lt;li&gt; Scale: The number of digits to the right of the decimal point.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Syntax:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;NUMBER[(precision, scale)]. *[ ] means optional
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;NUMBER Subtypes&lt;/strong&gt;&lt;br&gt;
The following are subtypes of NUMBER that can be used in PL/SQL:&lt;br&gt;
DEC&lt;br&gt;
DECIMAL&lt;br&gt;
DOUBLE PRECISION&lt;br&gt;
FLOAT&lt;br&gt;
INTEGER&lt;br&gt;
INT&lt;br&gt;
NUMERIC&lt;br&gt;
REAL&lt;br&gt;
SMALLINT&lt;/p&gt;

&lt;p&gt;These subtypes are useful because they provide names that are compatible with other programming languages. For example, you can use INT in your PL/SQL code, which is also recognized in languages like Java.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;PLS_INTEGER&lt;/strong&gt;&lt;br&gt;
PLS_INTEGER is a PL/SQL-specific data type used to store signed integers. It has a range from -2^31 to 2^31 - 1, or -2,147,483,648 to 2,147,483,647. Since PLS_INTEGER uses machine arithmetic, it requires less storage and is faster than NUMBER for integer operations.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Character Types&lt;/strong&gt;&lt;br&gt;
Character types allow us to store alphanumeric data.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;CHAR&lt;/strong&gt;&lt;br&gt;
The CHAR data type stores a fixed-length character string, with the maximum size being 32,767 bytes. If the stored string is shorter than the defined length, it will be padded with spaces to the right.&lt;/p&gt;

&lt;p&gt;Syntax&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;CHAR[(maximum_size [CHAR | BYTE])]
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;If you don’t specify the maximum size, it defaults to 1.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;VARCHAR2&lt;/strong&gt;&lt;br&gt;
The VARCHAR2 data type stores a varying-length character string, with the maximum size also being 32,767 bytes. Unlike CHAR, VARCHAR2 only uses the necessary amount of storage for the string and does not pad with spaces.&lt;/p&gt;

&lt;p&gt;Syntax&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;VARCHAR2(maximum_size [CHAR | BYTE])
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;em&gt;Difference Between CHAR and VARCHAR2&lt;/em&gt;&lt;br&gt;
The key difference between CHAR and VARCHAR2 is:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;CHAR stores a fixed-length string and pads the string with spaces on the right if it is shorter than the defined size.&lt;/li&gt;
&lt;li&gt;VARCHAR2 stores a variable-length string and does not pad the string with spaces.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Here’s an example:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;str1 CHAR(2) := ‘a’; — This will store ‘a ‘ (with a space)
str2 VARCHAR2(2) := ‘a’; — This will store ‘a’ (no space)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Boolean Type&lt;/strong&gt;&lt;br&gt;
The BOOLEAN data types store logical values: TRUE, FALSE, and NULL. PL/SQL supports the BOOLEAN type, but SQL does not. This means that BOOLEAN values cannot be used in SQL statements, built-in SQL functions, or PL/SQL functions invoked from SQL.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Datetime Types&lt;/strong&gt;&lt;br&gt;
&lt;strong&gt;DATE&lt;/strong&gt;&lt;br&gt;
The DATE data type stores date and time values. It includes both the date portion (year, month, day) and the time portion (hours, minutes, seconds).&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;The time portion is measured in seconds since midnight. &lt;/li&gt;
&lt;li&gt;If only the date is specified, the time portion defaults to midnight.&lt;/li&gt;
&lt;li&gt;The date portion defaults to the current date when no date is provided.&lt;/li&gt;
&lt;li&gt;The SYSDATE function returns the current date and time based on the server’s system clock. &lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;The default date format in Oracle is 'DD-MON-YY' (e.g., ‘01-OCT-25’).&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Cutoff Rule&lt;/em&gt;&lt;br&gt;
The  ‘01-OCT-25’ example represents October 1, 2025. But how does Oracle decide whether it’s 2025 or 1925? Oracle uses a default windowing rule to determine the century. The default cutoff year is 50:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;If the year is between 00 and 49, Oracle interprets it as 2000 to 2049. &lt;/li&gt;
&lt;li&gt;If the year is between 50 and 99, Oracle interprets it as 1950 to 1999. &lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;To avoid this ambiguity, it’s recommended to specify the year using four digits (e.g., ‘01-OCT-2025’) instead of two digits.&lt;/p&gt;

&lt;p&gt;These are the commonly used data types in PL/SQL. As I mentioned earlier, there are other types, including subtypes. Initially, I felt overwhelmed by the vast variety of available types, but now it’s becoming clearer to focus on the fundamental ones to start with. Since PL/SQL is all about handling data, it’s essential to understand the specific data types involved. Expanding our knowledge of each data type will definitely help improve our coding skills.&lt;/p&gt;

</description>
      <category>beginners</category>
      <category>database</category>
      <category>learning</category>
      <category>sql</category>
    </item>
    <item>
      <title>An Introduction to PL/SQL: How It Works with SQL and Oracle Database</title>
      <dc:creator>Ayako yk</dc:creator>
      <pubDate>Sun, 05 Oct 2025 03:24:30 +0000</pubDate>
      <link>https://forem.com/ayako_yk/an-introduction-to-plsql-how-it-works-with-sql-and-oracle-database-34cm</link>
      <guid>https://forem.com/ayako_yk/an-introduction-to-plsql-how-it-works-with-sql-and-oracle-database-34cm</guid>
      <description>&lt;p&gt;At a new company, PL/SQL is required to join the team. Although I’ve focused more on the front-end side, to become a full-stack developer, I plan to leverage my knowledge and skills in databases.&lt;/p&gt;

&lt;p&gt;I’ll start by covering the fundamentals. As I gain more experience and learn from my mistakes, I’ll dive into more advanced topics and practical cases.&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;What is PL/SQL?&lt;/li&gt;
&lt;li&gt;How It Works&lt;/li&gt;
&lt;li&gt;Block-Structured Language&lt;/li&gt;
&lt;li&gt;Nesting Blocks&lt;/li&gt;
&lt;li&gt;How to Run Blocks&lt;/li&gt;
&lt;li&gt;Naming Blocks&lt;/li&gt;
&lt;li&gt;SQL Code in PL/SQL Blocks&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;&lt;strong&gt;What is PL/SQL?&lt;/strong&gt;&lt;br&gt;
PL/SQL is an extension of SQL, designed specifically for the Oracle Database. PL/SQL stands for Procedural Language/ Structured Query Language. While SQL is declarative, meaning SQL itself determines how to execute a command (e.g., when selecting data, we just say &lt;code&gt;SELECT&lt;/code&gt;, and SQL returns the result), PL/SQL is imperative. This means we explicitly write the code that tells the system how to execute the command. PL/SQL is a more flexible and powerful data programming language. Note that PL/SQL can only be executed within the Oracle Database and is not designed for standalone languages like Java or C#.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;How It Works&lt;/strong&gt;&lt;br&gt;
PL/SQL code is compiled by the Oracle Database server and stored within the database. At run-time, both PL/SQL and SQL run within the same server process.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Block-Structured Language&lt;/strong&gt;&lt;br&gt;
PL/SQL is a block-structured language, similar to JavaScript. A PL/SQL block consists of three sections: Declarative, Executable, and Exception Handling, which are separated by the keywords DECLARE, BEGIN, EXCEPTION, and END.&lt;/p&gt;

&lt;p&gt;Example from &lt;a href="https://blogs.oracle.com/connect/post/building-with-blocks" rel="noopener noreferrer"&gt;the Oracle Documentation blog&lt;/a&gt;:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;DECLARE
    l_message
    VARCHAR2 (100) := ‘Hello World!’;
BEGIN
    DBMS_OUTPUT.put_line(l_message);
EXCEPTION
    WHEN OTHERS
    THEN
        DBMS_OUTPUT.put_line(SQLERRM);
END;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Section Explanations:&lt;br&gt;
&lt;strong&gt;Declarative&lt;/strong&gt;: This section contains statements to declare variables, constants, data types, and other code elements.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Executable&lt;/strong&gt;: This section contains statements that are executed when the block is run.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Exception handling&lt;/strong&gt;: This section handles errors and catches exceptions when they occur.&lt;/p&gt;

&lt;p&gt;The Declarative and exception-handling sections are optional. Only the Executable section is mandatory. Therefore, the following block is perfectly valid.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;BEGIN
    DBMS_OUTPUT.put_line(’Hello World!’);
END;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Nesting Blocks&lt;/strong&gt;&lt;br&gt;
PL/SQL blocks can be nested within other blocks.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;How to Run Blocks&lt;/strong&gt;&lt;br&gt;
There are various tools available for running PL/SQL blocks, and developers often have personal preferences.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;SQL*Plus&lt;/strong&gt;: This is a command-line interface that allows execution of both SQL and PL/SQL. It is often seen as a basic, no-frills tool provided by Oracle for executing SQL statements and PL/SQL blocks.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;IDEs&lt;/strong&gt;: These tools offer more features and enhance productivity. Popular IDEs for PL/SQL development include Oracle SQL Developer and PL/SQL Developer, which provide graphical interfaces that make writing, debugging, and managing PL/SQL code more efficient.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Naming Blocks&lt;/strong&gt;&lt;br&gt;
The blocks shared above don’t have names. They are called “anonymous blocks” and are often used as temporary PL/SQL units. On the other hand, named blocks, or subprograms, can be useful because they can be called multiple times without needing to declare or write the same repetitive code. They are similar to functions or methods in languages like JavaScript. &lt;/p&gt;

&lt;p&gt;Example:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;CREATE OR REPLACE FUNCTION
hello_message
    (place_in IN VARCHAR2)
    RETURN VARCHAR2
IS
BEGIN
    RETURN ‘Hello ‘ || place_in;
END hello_message;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The details will be explained later, but for now, it’s important to know that blocks can be named.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;SQL Code in PL/SQL Blocks&lt;/strong&gt;&lt;br&gt;
As mentioned earlier, both PL/SQL and SQL run within the same server process at runtime. Programs written in PL/SQL interact with the Oracle Database using SQL to read from or write to the database. The Oracle Database facilitates this by allowing SQL and PL/SQL to be combined seamlessly.&lt;/p&gt;

&lt;p&gt;Example from the Oracle documentation blog.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;DECLARE
    l_name employees.last_name%TYPE;
BEGIN
    SELECT last_name
        INTO l_name
        FROM employees
        WHERE employee_id = 138;

    DBMS_OUTPUT.put_line(l_name);
END;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The SELECT, FROM, and WHERE classes are SQL statements but can be used within PL/SQL blocks.&lt;/p&gt;

&lt;p&gt;In this blog post, I discussed what PL/SQL is, how it works, and its relationship with SQL and the Oracle Database. As I continue to learn, I may discover additional insights that I initially missed. I’ll revisit and update this post to ensure it provides the best possible understanding.&lt;/p&gt;

</description>
      <category>beginners</category>
      <category>database</category>
      <category>learning</category>
      <category>sql</category>
    </item>
    <item>
      <title>The Lifecycle of useEffect: Synchronization in React</title>
      <dc:creator>Ayako yk</dc:creator>
      <pubDate>Tue, 16 Sep 2025 01:20:06 +0000</pubDate>
      <link>https://forem.com/ayako_yk/the-lifecycle-of-useeffect-synchronization-in-react-1ge6</link>
      <guid>https://forem.com/ayako_yk/the-lifecycle-of-useeffect-synchronization-in-react-1ge6</guid>
      <description>&lt;p&gt;In previous blog posts, I discussed the foundation of the useEffect hook and when not to use it. In this post, I'll explore its lifecycle.&lt;/p&gt;

&lt;p&gt;&lt;code&gt;useEffect&lt;/code&gt; is primarily used to synchronize React components after side effects, which are operations outside of React's main rendering system. The Effect runs after the component mounts, so we should consider React's component lifecycle and useEffect's lifecycle separately. The React documentation mentions this in bold, which I'll share after this brief explanation.&lt;/p&gt;

&lt;p&gt;React components go through three stages: mount, update, and unmount. However, useEffect needs to synchronize less frequently or more frequently than the component's cycle.&lt;/p&gt;

&lt;p&gt;Here's an example from the &lt;a href="https://react.dev/learn/lifecycle-of-reactive-effects" rel="noopener noreferrer"&gt;React documentation&lt;/a&gt;. This component has a dropdown menu, where a user can choose a room ID: &lt;code&gt;general&lt;/code&gt;, &lt;code&gt;travel&lt;/code&gt;, or &lt;code&gt;music&lt;/code&gt;.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;function ChatRoom({ roomId /* "general" */ }) {
  useEffect(() =&amp;gt; {
    const connection = createConnection(serverUrl, roomId); // Connects to the "general" room
    connection.connect();
    return () =&amp;gt; {
      connection.disconnect(); // Disconnects from the "general" room
  };
}, [roomId]);
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Every time the &lt;code&gt;roomId&lt;/code&gt; changes, the Effect stops synchronizing with the old &lt;code&gt;roomId&lt;/code&gt; and starts synchronizing with the new one. React calls the cleanup function.&lt;br&gt;
Therefore, we should consider React's components and useEffect independently.&lt;/p&gt;

&lt;p&gt;The React documentation says:&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;[A]lways focus on a single start/stop cycle at a time. It shouldn’t matter whether a component is mounting, updating, or unmounting. All you need to do is to describe how to start synchronization and how to stop it. If you do it well, your Effect will be resilient to being started and stopped as many times as it’s needed.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;&lt;strong&gt;How to Tell React to Re-Synchronize&lt;/strong&gt;&lt;br&gt;
We can tell React when to re-synchronize by providing props or state in the dependency array. An empty dependency array means useEffect runs only when the component mounts.&lt;/p&gt;

&lt;p&gt;Each Effect Should Represent a Separate Synchronization Process&lt;br&gt;
We might be tempted to simplify code by combining functions to make it "cleaner." However, we should keep in mind that we will likely add more features and functions later on. So, each useEffect should contain only one logical operation.&lt;/p&gt;

&lt;p&gt;The &lt;code&gt;ChatRoom&lt;/code&gt; component has two distinct operations: one is logging the user's visit to the page, and the other is connecting to the server. Currently, it might be fine to combine them, as both are triggered when the roomId changes. However, as the component gains more features and the dependency array grows, this could lead to undesired behavior.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;function ChatRoom({ roomId }) {
  useEffect(() =&amp;gt; {
    logVisit(roomId);

    const connection = createConnection(serverUrl, roomId);
    connection.connect();
    return () =&amp;gt; {
      connection.disconnect();
    };
  }, [roomId]);
  ...
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Instead, we should separate them:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;function ChatRoom({ roomId }) {
  useEffect(() =&amp;gt; {
    logVisit(roomId);
  }, [roomId]);

  useEffect(() =&amp;gt; {
    const connection = createConnection(serverUrl, roomId);
    ...
}, [roomId]);
  ...
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Effect Should Re-Synchronize Whenever Reactive Values Change&lt;/strong&gt;&lt;br&gt;
Values declared in a component are all "reactive." This includes not only props and state but also variables that are calculated based on the change of props and state.&lt;/p&gt;

&lt;p&gt;Reactive values should re-synchronize with the effect because they change over time. Therefore, we should include those values in the dependency array.&lt;/p&gt;

&lt;p&gt;Here's an example from the React documentation:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;function ChatRoom({ roomId, selectedServerUrl }) { // roomId is reactive
    const settings = useContext(SettingsContext); // settings is reactive
    const serverUrl = selectedServerUrl ?? settings.defaultServerUrl; //    serverUrl is reactive
    useEffect(() =&amp;gt; {
      const connection = createConnection(serverUrl, roomId); // Your Effect reads roomId and serverUrl
      connection.connect();
      return () =&amp;gt; {
        connection.disconnect();
      };
    }, [roomId, serverUrl]); // So it needs to re-synchronize when either of them changes!
  ...
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Linter Will Warn You&lt;/strong&gt;&lt;br&gt;
When a linter is configured for React, it will throw an error if a dependency array is missing values. The linter isn't perfect and won't automatically fix the issue, but we should carefully read the error message and fix the code.&lt;/p&gt;

&lt;p&gt;To recap, we should consider the lifecycle of useEffect separately from the lifecycle of React components. Think of useEffect as handling two tasks: starting synchronization and stopping synchronization. Additionally, we should leverage the linter to catch potential issues, ensuring that we don't miss any bugs when building our application.&lt;/p&gt;

</description>
      <category>javascript</category>
      <category>react</category>
      <category>learning</category>
      <category>frontend</category>
    </item>
    <item>
      <title>When Not to Use useEffect in React</title>
      <dc:creator>Ayako yk</dc:creator>
      <pubDate>Sat, 06 Sep 2025 07:59:42 +0000</pubDate>
      <link>https://forem.com/ayako_yk/when-not-to-use-useeffect-in-react-210o</link>
      <guid>https://forem.com/ayako_yk/when-not-to-use-useeffect-in-react-210o</guid>
      <description>&lt;p&gt;In the last blog post, I discussed the foundation of useEffect. It is used to synchronize the React component with external systems. However, it's essential to understand that synchronization via useEffect should only occur after side effects have been executed. Unnecessary use of useEffect can lead to slow performance and potential errors. Below are some cases and examples where the unnecessary use of useEffect should be avoided.&lt;/p&gt;

&lt;p&gt;The content and examples are taken from the &lt;a href="https://react.dev/learn/you-might-not-need-an-effect" rel="noopener noreferrer"&gt;React documentation&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Updating State Based on Props or State&lt;/strong&gt;&lt;br&gt;
React re-renders whenever there's a state change, so using &lt;code&gt;useEffect&lt;/code&gt; to update the state based on a change in props or state is often unnecessary.&lt;/p&gt;

&lt;p&gt;Here's an example from the React Documentation, where &lt;code&gt;fullName&lt;/code&gt; should be updated whenever &lt;code&gt;firstName&lt;/code&gt; and &lt;code&gt;lastName&lt;/code&gt; change:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;function Form() {
  const [firstName, setFirstName] = useState('Taylor');
  const [lastName, setLastName] = useState('Swift');

  const [fullName, setFullName] = useState('');
  useEffect(() =&amp;gt; {
    setFullName(firstName + ' ' + lastName);
    }, [firstName, lastName]);
  ...
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Instead, fullName can be calculated during rendering:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;function Form() {
  const [firstName, setFirstName] = useState('Taylor');
  const [lastName, setLastName] = useState('Swift');

  const fullName = firstName + ' ' + lastName;
  ...
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Caching Expensive Calculations&lt;/strong&gt;&lt;br&gt;
When calculations are expensive --- meaning they take a significant amount of time to compute --- caching and avoiding unnecessary re-renders are recommended. We can achieve this by using &lt;code&gt;useMemo&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;Here's an example where we filter a to-do list based on the passed props. By using &lt;code&gt;useMemo&lt;/code&gt;, the calculation will only be re-rendered if the props change.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;function TodoList({ todos, filter }) {
  const [newTodo, setNewTodo] = useState('');
  const visibleTodos = useMemo(() =&amp;gt; {
    return getFilteredTodos(todos, filter);
  }, [todos, filter]);
  ...
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Resetting All State When a Prop Changes&lt;/strong&gt;&lt;br&gt;
When we have a state, such as comments for each user, and we need to reset the state every time the &lt;code&gt;userId&lt;/code&gt; changes (because we don't want to display the comment for other users), we might be tempted to use &lt;code&gt;useEffect&lt;/code&gt;. However, the code below is incorrect:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;export default function ProfilePage({ userId }) {
  const [comment, setComment] = useState('');

  useEffect(() =&amp;gt; {
    setComment('');
    }, [userId]);
    ...
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The issue is that React first renders the &lt;code&gt;comment&lt;/code&gt;, and then the &lt;code&gt;useEffect&lt;/code&gt; runs. This means the comment will be displayed before it's reset.&lt;br&gt;
We can fix this by passing the &lt;code&gt;userId&lt;/code&gt; as a &lt;code&gt;key&lt;/code&gt; in the parent component:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;export default function ProfilePage({ userId }) {
  return (
    &amp;lt;Profile
      userId={userId}
      key={userId}
    /&amp;gt;
  );
}

function Profile({ userId }) {
  const [comment, setComment] = useState('');
  ...
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Passing a key tells React to treat each &lt;code&gt;Profile&lt;/code&gt;component as independent, ensuring it resets properly when the &lt;code&gt;userId&lt;/code&gt; changes.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Adjusting Some State When a Prop Changes&lt;/strong&gt;&lt;br&gt;
When we want to reset or adjust a part of the state when a prop changes, but not all of it, we might be tempted to use useEffect.&lt;/p&gt;

&lt;p&gt;Here's an example from the React documentation. When the items prop changes, the selection should be reset, while &lt;code&gt;isReverse&lt;/code&gt; should remain the same:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;function List({ items }) {
  const [isReverse, setIsReverse] = useState(false);
  const [selection, setSelection] = useState(null);

  useEffect(() =&amp;gt; {
    setSelection(null);
    }, [items]);
    ...
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;With this code, React first renders the &lt;code&gt;selection&lt;/code&gt;, and then it is set to &lt;code&gt;null&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;One solution is to create an additional state to store the previous value:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;function List({ items }) {
  const [isReverse, setIsReverse] = useState(false);
  const [selection, setSelection] = useState(null);

  const [prevItems, setPrevItems] = useState(items);
    if (items !== prevItems) {
      setPrevItems(items);
      setSelection(null);
    }
  ...
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The React documentation mentions that this approach is better than using useEffect, but there's an even more efficient way:&lt;br&gt;
The following code calculates the state directly during rendering.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;function List({ items }) {
  const [isReverse, setIsReverse] = useState(false);
  const [selectedId, setSelectedId] = useState(null);

  const selection = items.find(item =&amp;gt; item.id === selectedId) ?? null;
  ...
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Sharing Logic Between Event Handlers&lt;/strong&gt;&lt;br&gt;
This code from the React documentation shows how to display a notification when a user buys a product by clicking either a "buy" button or a "checkout" button:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;function ProductPage({ product, addToCart }) {
  useEffect(() =&amp;gt; {
    if (product.isInCart) {
      showNotification(`Added ${product.name} to the shopping cart!`);
    }
  }, [product]);

  function handleBuyClick() {
    addToCart(product);
  }

  function handleCheckoutClick() {
    addToCart(product);
    navigateTo('/checkout');
  }
  ...
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In this code, &lt;code&gt;product&lt;/code&gt; is declared in the dependency array, so every time the user visits or refreshes the page, the notification is displayed. This is incorrect. The notification should only be shown as a result of a user action (like clicking a button). Therefore, it should be triggered inside an event handler, not in the useEffect.&lt;/p&gt;

&lt;p&gt;Here's how you can fix it:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;function ProductPage({ product, addToCart }) {
  function buyProduct() {
    addToCart(product);
    showNotification(`Added ${product.name} to the shopping cart!`);
  }

  function handleBuyClick() {
    buyProduct();
  }

  function handleCheckoutClick() {
    buyProduct();
    navigateTo('/checkout');
  }
  ...
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Sending a POST Request&lt;/strong&gt;&lt;br&gt;
How should we handle these two kinds of POST requests?&lt;br&gt;
One is to send an analytics event when the page mounts, and the other is to send a form submission when a submit button is clicked.&lt;/p&gt;

&lt;p&gt;Here's an example from the React documentation:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;function Form() {
  const [firstName, setFirstName] = useState('');
  const [lastName, setLastName] = useState('');

// Correct
  useEffect(() =&amp;gt; {
    post('/analytics/event', { eventName: 'visit_form' });
  }, []);

// Incorrect
  const [jsonToSubmit, setJsonToSubmit] = useState(null);
  useEffect(() =&amp;gt; {
    if (jsonToSubmit !== null) {
      post('/api/register', jsonToSubmit);
    }
  }, [jsonToSubmit]);

  function handleSubmit(e) {
    e.preventDefault();
    setJsonToSubmit({ firstName, lastName });
  }
  ...
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In the first case, useEffect is appropriate because the POST request should be sent when the page is displayed or mounted. In the second case, however, the POST request should be sent only when the user clicks the submit button. Therefore, it should be handled inside an event handler, not useEffect.&lt;/p&gt;

&lt;p&gt;Here's a correct version:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;function Form() {
  const [firstName, setFirstName] = useState('');
  const [lastName, setLastName] = useState('');

  useEffect(() =&amp;gt; {
    post('/analytics/event', { eventName: 'visit_form' });
  }, []);

  function handleSubmit(e) {
    e.preventDefault();
    post('/api/register', { firstName, lastName });
  }
  ...
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Chains of Computations&lt;/strong&gt;&lt;br&gt;
The code below uses multiple useEffect hooks, which trigger another useEffect when one state changes:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;function Game() {
  const [card, setCard] = useState(null);
  const [goldCardCount, setGoldCardCount] = useState(0);
  const [round, setRound] = useState(1);
  const [isGameOver, setIsGameOver] = useState(false);

  useEffect(() =&amp;gt; {
    if (card !== null &amp;amp;&amp;amp; card.gold) {
      setGoldCardCount(c =&amp;gt; c + 1);
    }
  }, [card]);

  useEffect(() =&amp;gt; {
    if (goldCardCount &amp;gt; 3) {
      setRound(r =&amp;gt; r + 1)
      setGoldCardCount(0);
    }
  }, [goldCardCount]);

  useEffect(() =&amp;gt; {
    if (round &amp;gt; 5) {
      setIsGameOver(true);
    }
  }, [round]);

  useEffect(() =&amp;gt; {
    alert('Good game!');
  }, [isGameOver]);

  function handlePlaceCard(nextCard) {
    if (isGameOver) {
      throw Error('Game already ended.');
    } else {
      setCard(nextCard);
    }
  }
...
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This approach is not only inefficient but also prone to errors as the logic evolves (e.g., when tracking past state changes).&lt;br&gt;
It's better to calculate and adjust the state within the event handler, rather than using useEffect.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;function Game() {
  const [card, setCard] = useState(null);
  const [goldCardCount, setGoldCardCount] = useState(0);
  const [round, setRound] = useState(1);

  const isGameOver = round &amp;gt; 5;

  function handlePlaceCard(nextCard) {
    if (isGameOver) {
    throw Error('Game already ended.');
  }

  setCard(nextCard);
  if (nextCard.gold) {
    if (goldCardCount &amp;lt;= 3) {
      setGoldCardCount(goldCardCount + 1);
    } else {
      setGoldCardCount(0);
      setRound(round + 1);
      if (round === 5) {
        alert('Good game!');
      }
    }
  }
} 
...
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In some cases, such as when showing a dropdown menu, we might still need a chain of useEffect hooks. However, we should first consider whether it can be calculated directly in the event handler instead of relying on multiple useEffect hooks.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Initializing the Application&lt;/strong&gt;&lt;br&gt;
When you have logic that should run only once when an app is initially loaded, you might be tempted to include a useEffect hook at the top level in App.js.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;function App() {
  useEffect(() =&amp;gt; {
    loadDataFromLocalStorage();
    checkAuthToken();
  }, []);
  ...
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;However, React runs twice in Strict Mode, which can lead to unexpected behavior. Even though the code runs only once in production, it's still best to avoid this pattern.&lt;/p&gt;

&lt;p&gt;One solution is to declare a variable that tracks whether the initialization has already occurred:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;let didInit = false;

function App() {
  useEffect(() =&amp;gt; {
    if (!didInit) {
      didInit = true;
      loadDataFromLocalStorage();
      checkAuthToken();
    }
  }, []);
  ...
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Notifying Parents of State Changes&lt;/strong&gt;&lt;br&gt;
If you have a toggle that is triggered by either clicking or dragging, you might want to use the useEffect hook to change the state when the props change. However, this approach is incorrect because the state is rendered first, and then useEffect is run.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;function Toggle({ onChange }) {
  const [isOn, setIsOn] = useState(false);

  useEffect(() =&amp;gt; {
    onChange(isOn);
  }, [isOn, onChange])

  function handleClick() {
    setIsOn(!isOn);
  }

  function handleDragEnd(e) {
    if (isCloserToRightEdge(e)) {
      setIsOn(true);
    } else {
      setIsOn(false);
    }
  }
  ...
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Rather than using useEffect, we should have an updating function and include it in both handlers:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;function Toggle({ onChange }) {
  const [isOn, setIsOn] = useState(false);

  function updateToggle(nextIsOn) {
    setIsOn(nextIsOn);
    onChange(nextIsOn);
  }

  function handleClick() {
    updateToggle(!isOn);
  }

  function handleDragEnd(e) {
    if (isCloserToRightEdge(e)) {
      updateToggle(true);
    } else {
      updateToggle(false);
    }
  }
...
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Alternatively, we can lift the state up and let the parent component control the state:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;function Toggle({ isOn, onChange }) {
  function handleClick() {
  onChange(!isOn);
}

function handleDragEnd(e) {
  if (isCloserToRightEdge(e)) {
    onChange(true);
  } else {
    onChange(false);
  }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Passing Data to the Parent&lt;/strong&gt;&lt;br&gt;
In this example, the child component is trying to fetch data and pass it to its parent component.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;function Parent() {
  const [data, setData] = useState(null);
  ...
  return &amp;lt;Child onFetched={setData} /&amp;gt;;
}

function Child({ onFetched }) {
  const data = useSomeAPI();

  useEffect(() =&amp;gt; {
    if (data) {
      onFetched(data);
    }
  }, [onFetched, data]);
...
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;However, this approach goes against React's general pattern of data flow. In React, data typically flows downward from parent to child components, not the other way around. Instead, the parent should pass the data down to its child components.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Subscribing to an External Store&lt;/strong&gt;&lt;br&gt;
In some cases, you might need to subscribe to data outside of React's state, such as data from a third-party library or a built-in API. Since this data can change without React's knowledge, you need to manually subscribe to it. This is typically done using the useEffect hook.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;function useOnlineStatus() {
  const [isOnline, setIsOnline] = useState(true);
  useEffect(() =&amp;gt; {
    function updateState() {
      setIsOnline(navigator.onLine);
    }

    updateState();

    window.addEventListener('online', updateState);
    window.addEventListener('offline', updateState);
    return () =&amp;gt; {
      window.removeEventListener('online', updateState);
      window.removeEventListener('offline', updateState);
    };
  }, []);
  return isOnline;
}

function ChatIndicator() {
  const isOnline = useOnlineStatus();
...
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This is a common pattern for subscribing to external data, but React provides a purpose-built hook for subscribing to external stores: &lt;code&gt;useSyncExternalStore&lt;/code&gt;. This approach is less error-prone than manually subscribing to mutable data in useEffect.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;function subscribe(callback) {
  window.addEventListener('online', callback);
  window.addEventListener('offline', callback);
  return () =&amp;gt; {
    window.removeEventListener('online', callback);
    window.removeEventListener('offline', callback);
  };
}

function useOnlineStatus() {
  return useSyncExternalStore(
    subscribe,
    () =&amp;gt; navigator.onLine,
    () =&amp;gt; true
  );
}

function ChatIndicator() {
  const isOnline = useOnlineStatus();
  ...
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Fetching Data&lt;/strong&gt;&lt;br&gt;
The &lt;code&gt;SearchResult&lt;/code&gt; component fetches data when the query or page prop changes. This logic should be placed inside useEffect, not an event handler.&lt;/p&gt;

&lt;p&gt;While the user types a search query, there's a risk of a race condition. This happens because each character typed triggers a new fetch request, and responses might come back in an unexpected order. For example, if the user types quickly, the requests may arrive out of order, leading to incorrect results being displayed. This is called a "race condition":&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;two different requests 'raced' against each other and came in a different order than you expected.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;To fix this issue, a cleanup function is needed to ignore outdated responses. This ensures that only the results of the last requested fetch are displayed.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;function SearchResults({ query }) {
  const [results, setResults] = useState([]);
  const [page, setPage] = useState(1);
  useEffect(() =&amp;gt; {
    let ignore = false;
    fetchResults(query, page).then(json =&amp;gt; {
      if (!ignore) {
      setResults(json);
      }
    });
    return () =&amp;gt; {
      ignore = true;
    };
  }, [query, page]);

  function handleNextPageClick() {
    setPage(page + 1);
  }
  ...
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;With this cleanup function in place, only the latest search query or the last fetch request will update the state, ensuring the user sees the correct results.&lt;/p&gt;

&lt;p&gt;In the previous blog post, we explored the fundamental uses of useEffect, and it's easy to feel tempted to use it whenever it seems applicable. However, it's important to fully understand why and when the useEffect hook is necessary, and to use it correctly.&lt;/p&gt;

</description>
      <category>javascript</category>
      <category>react</category>
      <category>learning</category>
      <category>frontend</category>
    </item>
    <item>
      <title>Understanding useEffect in React: Managing Side Effects and Cleanup</title>
      <dc:creator>Ayako yk</dc:creator>
      <pubDate>Mon, 25 Aug 2025 01:15:22 +0000</pubDate>
      <link>https://forem.com/ayako_yk/understanding-useeffect-in-react-managing-side-effects-and-cleanup-55p6</link>
      <guid>https://forem.com/ayako_yk/understanding-useeffect-in-react-managing-side-effects-and-cleanup-55p6</guid>
      <description>&lt;p&gt;React often requires us to manage and synchronize operations outside of its rendering process. In the upcoming blogs, we'll dive into how &lt;code&gt;useEffect&lt;/code&gt; helps handle side effects in React.&lt;/p&gt;

&lt;p&gt;React has two types of core logic, which are important to understand before diving into Effects:&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Rendering Code&lt;/strong&gt;:&lt;br&gt;
This sits at the top level of a component and returns JSX. It must be pure --- like a mathematical formula, it only calculates and returns a result without causing any side effects.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Event Handlers&lt;/strong&gt;:&lt;br&gt;
These are nested functions that respond to user interactions, such as button clicks. Event handlers can change state or perform other actions, causing side effects (e.g., updating an input, making a network request, or navigating to another page).&lt;/p&gt;

&lt;p&gt;React mounts on initial rendering and whenever there is a change in state. However, there are cases when a render is needed even without a state change or event handler. This can happen due to side effects that require a re-render.&lt;/p&gt;

&lt;p&gt;Side effects are operations that happen outside of the main rendering process. They might include modifying non-local variables, raising errors, modifying the DOM, or interacting with external systems (like connecting to a server).&lt;/p&gt;

&lt;p&gt;To synchronize React components after side effects, the Effect hook comes into play.&lt;/p&gt;

&lt;p&gt;&lt;code&gt;useEffect&lt;/code&gt;&lt;br&gt;
&lt;code&gt;useEffect&lt;/code&gt; delays the execution of the code inside it.&lt;br&gt;
First, a component or a page is rendered.&lt;br&gt;
After that, the code inside the &lt;code&gt;useEffect&lt;/code&gt; is executed.&lt;/p&gt;

&lt;p&gt;Here's an example from the &lt;a href="https://react.dev/learn/synchronizing-with-effects#step-1-declare-an-effect" rel="noopener noreferrer"&gt;React Documentation&lt;/a&gt;:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;function VideoPlayer({ src, isPlaying }) {
  const ref = useRef(null);

  if (isPlaying) {
    ref.current.play();  // Calling these while rendering isn't allowed.
  } else {
    ref.current.pause(); // Also, this crashes.
  }

  return &amp;lt;video ref={ref} src={src} loop playsInline /&amp;gt;;
}

export default function App() {
  const [isPlaying, setIsPlaying] = useState(false);
  return (
    &amp;lt;&amp;gt;
      &amp;lt;button onClick={() =&amp;gt; setIsPlaying(!isPlaying)}&amp;gt;
        {isPlaying ? 'Pause' : 'Play'}
      &amp;lt;/button&amp;gt;
      &amp;lt;VideoPlayer
        isPlaying={isPlaying}
        src="https://interactive-examples.mdn.mozilla.net/media/cc0-videos/flower.mp4"
      /&amp;gt;
    &amp;lt;/&amp;gt;
  );
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This code won't work because it tries to access the &lt;code&gt;ref&lt;/code&gt; while the component is being rendered before the DOM element is available. The &lt;code&gt;ref&lt;/code&gt; of the DOM element doesn't exist yet. To fix this, we need to let the component render first and then execute the side effects using useEffect:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;useEffect(() =&amp;gt; {
  if (isPlaying) {
    ref.current.play();
  } else {
    ref.current.pause();
  }
});
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;The Importance of Cleanup&lt;/strong&gt;&lt;br&gt;
When code that connects to a server is placed inside &lt;code&gt;useEffect&lt;/code&gt;, it is executed when the component is mounted. If a user navigates to another component and then returns to the original one, this code is executed again, causing new connections to be queued. This can lead to bugs.&lt;/p&gt;

&lt;p&gt;To fix this, we need to disconnect the server or perform a cleanup of the connection.&lt;/p&gt;

&lt;p&gt;Here's an example from the React Documentation:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;export default function ChatRoom() {
  useEffect(() =&amp;gt; {
    const connection = createConnection();
    connection.connect();
    return () =&amp;gt; connection.disconnect();
  }, []);
  return &amp;lt;h1&amp;gt;Welcome to the chat!&amp;lt;/h1&amp;gt;;
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In React Strict Mode (enabled by default in development), React intentionally runs certain lifecycle methods, like &lt;code&gt;useEffect&lt;/code&gt;, twice to help developers identify issues and ensure code behaves correctly.&lt;/p&gt;

&lt;p&gt;There's much more to learn about &lt;code&gt;useEffect&lt;/code&gt; in React. While the React documentation categorizes some of these concepts as "advanced," it's essential for developers to gain a deep understanding of how React works.&lt;/p&gt;

</description>
      <category>javascript</category>
      <category>react</category>
      <category>learning</category>
      <category>frontend</category>
    </item>
    <item>
      <title>Understanding State Management with useReducer in React</title>
      <dc:creator>Ayako yk</dc:creator>
      <pubDate>Sun, 17 Aug 2025 22:13:31 +0000</pubDate>
      <link>https://forem.com/ayako_yk/understanding-state-management-with-usereducer-in-react-45l0</link>
      <guid>https://forem.com/ayako_yk/understanding-state-management-with-usereducer-in-react-45l0</guid>
      <description>&lt;p&gt;In the previous blog posts, I discussed state management and how it works with useState. In this post, I'll cover useReducer and how to manage state in React.&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;What is a Reducer?&lt;/li&gt;
&lt;li&gt;Why do we use it?&lt;/li&gt;
&lt;li&gt;How Reducer Works&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;&lt;strong&gt;What is a Reducer?&lt;/strong&gt;&lt;br&gt;
A &lt;strong&gt;reducer&lt;/strong&gt; is a function used with the &lt;code&gt;useReducer&lt;/code&gt; hook, which needs to be imported at the top of your file.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const [state, dispatch] = useReducer(reducer, initialArg, init?)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Why do we use it?&lt;/strong&gt;&lt;br&gt;
As an app grows larger and more state variables are required across multiple components, it becomes harder to manage, test, and debug them. While &lt;code&gt;useState&lt;/code&gt; and &lt;code&gt;useReducer&lt;/code&gt; are similar in functionality, &lt;code&gt;useReducer&lt;/code&gt; can make our code easier to handle. By using a reducer, we can create a separate file that contains only the reducer function instead of writing it in each component. This reduces the amount of code within individual components, which is one of the reasons why it is called a "reducer."&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;How Reducer Works&lt;/strong&gt;&lt;br&gt;
With &lt;code&gt;useState&lt;/code&gt;, we update the state by using an updater function (e.g., &lt;code&gt;setUser&lt;/code&gt; in the example below):&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const [user, setUser] = useState('');
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;With &lt;code&gt;useReducer&lt;/code&gt;, we dispatch an action that describes what the user did, along with the current state. The reducer function then processes the action and returns the updated state. &lt;/p&gt;

&lt;p&gt;Let's take a look at the example shared in the &lt;a href="https://react.dev/learn/extracting-state-logic-into-a-reducer" rel="noopener noreferrer"&gt;React Documentation&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;This app contains a &lt;code&gt;TaskApp&lt;/code&gt; component that handles adding, editing, and deleting tasks for a trip to Prague.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fhfhcl10jnwgaukrhpagf.jpeg" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fhfhcl10jnwgaukrhpagf.jpeg" alt=" " width="800" height="399"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;This component has three event handlers (for adding, editing, and deleting) to update the state (&lt;code&gt;setTasks&lt;/code&gt;).&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;export default function TaskApp() {
  const [tasks, setTasks] = useState(initialTasks);

  function handleAddTask(text) {
    setTasks([
      ...tasks,
      {
        id: nextId++,
        text: text,
        done: false,
      },
    ]);
  }

  function handleChangeTask(task) {
    setTasks(
      tasks.map((t) =&amp;gt; {
        if (t.id === task.id) {
          return task;
        } else {
          return t;
        }
      })
    );
  }

  function handleDeleteTask(taskId) {
    setTasks(tasks.filter((t) =&amp;gt; t.id !== taskId));
  }
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;It's better to write these functions in a separate file, so here's the &lt;code&gt;tasksReducer.js&lt;/code&gt; file:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;function tasksReducer(tasks, action) {
  switch (action.type) {
    case 'added': {
      return [
        ...tasks,
        {
          id: action.id,
          text: action.text,
          done: false,
        },
      ];
    }
    case 'changed': {
      return tasks.map((t) =&amp;gt; {
        if (t.id === action.task.id) {
          return action.task;
        } else {
          return t;
        }
      });
    }
    case 'deleted': {
      return tasks.filter((t) =&amp;gt; t.id !== action.id);
    }
    default: {
      throw Error('Unknown action: ' + action.type);
    }
  }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;A reducer function needs two parameters: one is the current &lt;code&gt;state&lt;/code&gt; (&lt;code&gt;tasks&lt;/code&gt;) and the other is the &lt;code&gt;action&lt;/code&gt;. The action is an object that contains a &lt;code&gt;type&lt;/code&gt; (which describes the action the user performed) and additional data, such as &lt;code&gt;id&lt;/code&gt; or &lt;code&gt;task&lt;/code&gt;, that the reducer function needs. The reducer function returns the updated (or &lt;code&gt;next&lt;/code&gt;) state.&lt;/p&gt;

&lt;p&gt;In each component, we declare &lt;code&gt;useReducer&lt;/code&gt; at the top of the file:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const [tasks, dispatch] = useReducer(tasksReducer, initialTasks);
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;We then use the dispatch function in an event handler.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import { useReducer } from 'react';
import AddTask from './AddTask.js';
import TaskList from './TaskList.js';
import tasksReducer from './tasksReducer.js';

export default function TaskApp() {
  const [tasks, dispatch] = useReducer(tasksReducer, initialTasks);

  function handleAddTask(text) {
    dispatch({
      type: 'added',
      id: nextId++,
      text: text,
    });
  }

  function handleChangeTask(task) {
    dispatch({
      type: 'changed',
      task: task,
    });
  }

  function handleDeleteTask(taskId) {
    dispatch({
      type: 'deleted',
      id: taskId,
    });
  }

  return (
    &amp;lt;&amp;gt;
      &amp;lt;h1&amp;gt;Prague itinerary&amp;lt;/h1&amp;gt;
      &amp;lt;AddTask onAddTask={handleAddTask} /&amp;gt;
      &amp;lt;TaskList
        tasks={tasks}
        onChangeTask={handleChangeTask}
        onDeleteTask={handleDeleteTask}
      /&amp;gt;
    &amp;lt;/&amp;gt;
  );
}

let nextId = 3;
const initialTasks = [
  {id: 0, text: 'Visit Kafka Museum', done: true},
  {id: 1, text: 'Watch a puppet show', done: false},
  {id: 2, text: 'Lennon Wall pic', done: false},
];
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Two important rules when we use useReducer&lt;/strong&gt;:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;
&lt;strong&gt;Reducers must be pure&lt;/strong&gt;: This means that for the same inputs, the reducer must always return the same outputs, with no side effects.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Each action describes a single user interaction&lt;/strong&gt;: This means one action should handle one specific task or change, even if that task leads to multiple changes in the data.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Even though &lt;code&gt;useReducer&lt;/code&gt; may seem more complex at first glance due to its additional code and structure compared to useState, it ultimately makes the code more readable and manageable in larger applications.&lt;/p&gt;

</description>
      <category>javascript</category>
      <category>react</category>
      <category>learning</category>
      <category>frontend</category>
    </item>
    <item>
      <title>Understanding State in React: Managing State Between Components</title>
      <dc:creator>Ayako yk</dc:creator>
      <pubDate>Tue, 12 Aug 2025 15:19:59 +0000</pubDate>
      <link>https://forem.com/ayako_yk/understanding-state-in-react-managing-state-between-components-4iae</link>
      <guid>https://forem.com/ayako_yk/understanding-state-in-react-managing-state-between-components-4iae</guid>
      <description>&lt;p&gt;In my previous blog post, I covered the fundamentals of state in React, including concepts like state as a snapshot, batching, and updating states. In this post, I'll dive deeper into state management, focusing on how to manage state between components.&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Declarative vs. Imperative&lt;/li&gt;
&lt;li&gt;Lifting State Up&lt;/li&gt;
&lt;li&gt;React's State and the Render Tree&lt;/li&gt;
&lt;li&gt;Component State and React's Behavior&lt;/li&gt;
&lt;li&gt;State Preservation&lt;/li&gt;
&lt;li&gt;State Destruction&lt;/li&gt;
&lt;li&gt;Rendering Different Components&lt;/li&gt;
&lt;li&gt;Using "key" to Preserve State&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;&lt;strong&gt;Declarative vs. Imperative&lt;/strong&gt;&lt;br&gt;
React is declarative, not imperative. This means that instead of telling React exactly how to update the UI, you simply declare what the UI should look like based on the current state. React then takes care of the rest. &lt;/p&gt;

&lt;p&gt;For example, if the state &lt;code&gt;isOpen&lt;/code&gt; is true, React will display a hamburger menu; if the state is false, it will hide the menu.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Lifting State Up&lt;/strong&gt;&lt;br&gt;
When two separate components need to share and manage the same state, it's a good practice to "lift" the state up. This means moving the state to their closest common parent component and passing it down to the child components via props. This achieves a single source of truth for the state. &lt;/p&gt;

&lt;p&gt;Components with props passed down are called &lt;strong&gt;controlled&lt;/strong&gt;, while components that manage their own states are called &lt;strong&gt;uncontrolled&lt;/strong&gt;.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Component State and React's Behavior&lt;/strong&gt;&lt;br&gt;
When you render the same component multiple times, each instance of the component is independent and holds its own state, which doesn't affect the other instances.&lt;/p&gt;

&lt;p&gt;Here's an example from &lt;a href="https://react.dev/learn/preserving-and-resetting-state#state-is-tied-to-a-position-in-the-tree" rel="noopener noreferrer"&gt;React's documentation&lt;/a&gt;:&lt;br&gt;
(The code has been simplified for clarity.)&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;export default function App() {
  const counter = &amp;lt;Counter /&amp;gt;;
  return (
    &amp;lt;div&amp;gt;
      {counter}
      {counter}
    &amp;lt;/div&amp;gt;
  );
}

function Counter() {
  const [score, setScore] = useState(0);
  return (
    &amp;lt;div&amp;gt;
      &amp;lt;h1&amp;gt;{score}&amp;lt;/h1&amp;gt;
      &amp;lt;button onClick={() =&amp;gt; setScore(score + 1)}&amp;gt;
        Add one
      &amp;lt;/button&amp;gt;
    &amp;lt;/div&amp;gt;
  );
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Here's an image of the React component tree.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F4syi56oqqyqn1ry8mppq.jpeg" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F4syi56oqqyqn1ry8mppq.jpeg" alt=" " width="800" height="575"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;State Preservation&lt;/strong&gt;&lt;br&gt;
React keeps the state for as long as the same component is re-rendered at the same position in the render tree.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;State Destruction&lt;/strong&gt;&lt;br&gt;
When the component is unmounted, the state is destroyed. When it is mounted again, the state is initialized.&lt;/p&gt;

&lt;p&gt;The "Render the second counter" checkbox removes the second component and creates a new one.&lt;/p&gt;

&lt;p&gt;Example:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fr0azppesqrep58yckyb7.jpeg" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fr0azppesqrep58yckyb7.jpeg" alt=" " width="800" height="388"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fl4j002bxhawgdkz6h1hg.jpeg" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fl4j002bxhawgdkz6h1hg.jpeg" alt=" " width="800" height="467"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;If the same component is rendered at the same position (e.g., by conditional state), the state is preserved.&lt;/p&gt;

&lt;p&gt;Example:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;export default function App() {
  const [isFancy, setIsFancy] = useState(false); // Fancy adds fancy styles
  return (
    &amp;lt;div&amp;gt;
      {isFancy ? (
        &amp;lt;Counter isFancy={true} /&amp;gt; 
      ) : (
        &amp;lt;Counter isFancy={false} /&amp;gt; 
      )}
    &amp;lt;/div&amp;gt;
  );
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Rendering Different Components&lt;/strong&gt;&lt;br&gt;
Rendering different components at the same position resets the state, as React treats them as separate instances.&lt;br&gt;
In this example, different components are rendered depending on the condition: one is &lt;code&gt;&amp;lt;p&amp;gt;&lt;/code&gt;, and the other is &lt;code&gt;&amp;lt;Count /&amp;gt;&lt;/code&gt;. This will reset the state.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;export default function App() {
  const [isPaused, setIsPaused] = useState(false);
  return (
    &amp;lt;div&amp;gt;
      {isPaused ? (
        &amp;lt;p&amp;gt;See you later!&amp;lt;/p&amp;gt; 
      ) : (
        &amp;lt;Counter /&amp;gt; 
      )}
    &amp;lt;/div&amp;gt;
  );
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Using &lt;code&gt;key&lt;/code&gt; to Preserve State&lt;/strong&gt;&lt;br&gt;
To preserve the state for each component, we can either render them at different positions in the tree or assign a unique key to each component.&lt;/p&gt;

&lt;p&gt;The use case is when we want to keep separate counters for different people: Person A's counter and Person B's counter. We don't want to display Person A's counter for Person B. By giving a unique key to each component, React can distinguish between them.&lt;br&gt;
Here's an example from the React documentation:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;export default function Scoreboard() {
  const [isPlayerA, setIsPlayerA] = useState(true);
  return (
    &amp;lt;div&amp;gt;
      {isPlayerA ? (
        &amp;lt;Counter key="Taylor" person="Taylor" /&amp;gt;
      ) : (
        &amp;lt;Counter key="Sarah" person="Sarah" /&amp;gt;
      )}
      &amp;lt;button onClick={() =&amp;gt; {
        setIsPlayerA(!isPlayerA);
      }}&amp;gt;
        Next player!
      &amp;lt;/button&amp;gt;
    &amp;lt;/div&amp;gt;
  );
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Note that when switching from Person B back to Person A, the state is reinitialized.&lt;/p&gt;

&lt;p&gt;The latest React documentation explains things so well that it gave me a much clearer understanding of how React treats state. I only wish I had known this when I first started learning React. I hope you found this article helpful, and I encourage you to visit the React documentation for more details and further practice (it also offers challenges to deepen your understanding).&lt;/p&gt;

</description>
      <category>javascript</category>
      <category>tutorial</category>
      <category>react</category>
      <category>learning</category>
    </item>
  </channel>
</rss>
