<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by kahmun on Medium]]></title>
        <description><![CDATA[Stories by kahmun on Medium]]></description>
        <link>https://medium.com/@mun1013?source=rss-4e6df3e6ef0c------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*Vl3CltF3jliLZYu0GYRIKQ.jpeg</url>
            <title>Stories by kahmun on Medium</title>
            <link>https://medium.com/@mun1013?source=rss-4e6df3e6ef0c------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 13:14:25 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@mun1013/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[React + TypeScript — Part 2]]></title>
            <link>https://medium.com/@mun1013/react-typescript-part-2-bae53ef4e26d?source=rss-4e6df3e6ef0c------2</link>
            <guid isPermaLink="false">https://medium.com/p/bae53ef4e26d</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[frontend-development]]></category>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[react-typescript]]></category>
            <dc:creator><![CDATA[kahmun]]></dc:creator>
            <pubDate>Sat, 14 Sep 2024 08:04:00 GMT</pubDate>
            <atom:updated>2024-09-14T08:06:04.175Z</atom:updated>
            <content:encoded><![CDATA[<h3>React + TypeScript — Part 2</h3><p>Let’s continue from the earlier post, which focuses on <strong>type alias</strong>, <strong>children prop</strong>, <strong>useState</strong>, <strong>useRef</strong>, <strong>dynamic component</strong>, <strong>wrapper component</strong> and <strong>polymorphic component</strong>.</p><p><a href="https://medium.com/@mun1013/react-typescript-part-1-94d5da740c2d">React + TypeScript — Part 1</a></p><p>In this post, let’s dive further.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*46ekEGz0hJigGA20f7-XUA.jpeg" /></figure><h4>👉 useEffect</h4><p>It doesn’t make much difference when using <strong>useEffect</strong> with TypeScript. Given the example below for data fetching.</p><pre>import { useEffect, useState, type ReactNode } from &quot;react&quot;;<br><br>function App() {<br>  const [data, setData] = useState&lt;unknown&gt;(); <br>  const [isFetching, setIsFetching] = useState&lt;boolean&gt;(false);<br>  const [error, setError] = useState&lt;string&gt;();<br><br>  useEffect(() =&gt; {<br>    async function fetchedPosts() {<br>      setIsFetching(true);<br>      try {<br>        const data = (await get(&#39;https://abc.com/posts&#39;)) as unknown;<br>        setData(data);<br>      } catch (error) {<br>        if (error instanceof Error) {<br>          setError(error.message);<br>        }<br>      }<br>      setIsFetching(false);<br>    }<br><br>    fetchedPosts();<br>  }, []);<br><br>  return (<br>    {isFetching &amp;&amp; &lt;p&gt;Loading...&lt;/p&gt;}<br>      {error &amp;&amp; &lt;p&gt;Error: {error}&lt;/p&gt;}<br>      {data &amp;&amp; data.map(post =&gt; (<br>        &lt;div key={post.id}&gt;<br>          &lt;h2&gt;{post.title}&lt;/h2&gt;<br>          &lt;p&gt;{post.description}&lt;/p&gt;<br>        &lt;/div&gt;<br>     ))}<br>  );<br>}<br><br>export default App;</pre><p>TypeScript has no idea of what kind of data returned by the server. Using <strong>unknown</strong> type is actually better than <strong>any</strong> because the TypeScript compiler would not check the type of the value at all if we define it as <strong>any</strong>.</p><p>However, it is better to define it if the type is known, as below. This provides clarity and helps prevent errors.</p><pre>import { useEffect, useState, type ReactNode } from &quot;react&quot;;<br><br>type Post= {<br>  id: number;<br>  title: string;<br>  description: string;<br>}<br><br>function App() {<br>  const [data, setData] = useState&lt;Post[]&gt;(); <br>  const [isFetching, setIsFetching] = useState&lt;boolean&gt;(false);<br>  const [error, setError] = useState&lt;string&gt;();<br><br>  useEffect(() =&gt; {<br>    async function fetchedPosts() {<br>      setIsFetching(true);<br>      try {<br>        const data = (await get(&#39;https://abc.com/posts&#39;)) as Post[];<br>        setData(data);<br>      } catch (error) {<br>        if (error instanceof Error) {<br>          setError(error.message);<br>        }<br>      }<br>      setIsFetching(false);<br>    }<br><br>    fetchedPosts();<br>  }, []);<br><br>  return (<br>    {isFetching &amp;&amp; &lt;p&gt;Loading...&lt;/p&gt;}<br>      {error &amp;&amp; &lt;p&gt;Error: {error}&lt;/p&gt;}<br>      {data &amp;&amp; data.map(post =&gt; (<br>        &lt;div key={post.id}&gt;<br>          &lt;h2&gt;{post.title}&lt;/h2&gt;<br>          &lt;p&gt;{post.description}&lt;/p&gt;<br>        &lt;/div&gt;<br>     ))}<br>  );<br>}<br><br>export default App;</pre><p>Alternatively, <a href="https://zod.dev/?id=introduction"><strong>Zod</strong></a><strong> </strong>is a great option. This library can be used to parse and validate the data you are working with. All you need is to provide a <strong>schema </strong>to Zod and it will validate the data at runtime and provides error messages when the data doesn’t match the expected schema.</p><pre>import { useEffect, useState, type ReactNode } from &quot;react&quot;;<br>import { z } from &quot;zod&quot;;<br><br>// Define a Zod schema for a Post object<br>const PostSchema = z.object({<br>  id: z.number(),<br>  title: z.string(),<br>  description: z.string(),<br>});<br><br>// Define a schema for an array of posts<br>const PostsSchema = z.array(PostSchema);<br><br>// Define the Post type using Zod&#39;s inference<br>type Post = z.infer&lt;typeof PostSchema&gt;;<br><br>function App() {<br>  const [data, setData] = useState&lt;Post[] | null&gt;(null);<br>  const [isFetching, setIsFetching] = useState&lt;boolean&gt;(false);<br>  const [error, setError] = useState&lt;string | null&gt;(null);<br><br>  useEffect(() =&gt; {<br>    async function fetchedPosts() {<br>      setIsFetching(true);<br>      try {<br>        const response = await fetch(&#39;https://abc.com/posts&#39;);<br>        const jsonData = await response.json();<br><br>        // Use Zod to validate the response data<br>        const result = PostsSchema.safeParse(jsonData);<br><br>        if (result.success) {<br>          setData(result.data);<br>        } else {<br>          setError(&quot;Data validation error&quot;);<br>          console.error(result.error);<br>        }<br>      } catch (error) {<br>        if (error instanceof Error) {<br>          setError(error.message);<br>        }<br>      } finally {<br>        setIsFetching(false);<br>      }<br>    }<br><br>    fetchedPosts();<br>  }, []);<br><br>  return (<br>    &lt;main&gt;<br>      {isFetching &amp;&amp; &lt;p&gt;Loading...&lt;/p&gt;}<br>      {error &amp;&amp; &lt;p&gt;Error: {error}&lt;/p&gt;}<br>      {data &amp;&amp; data.map(post =&gt; (<br>        &lt;div key={post.id}&gt;<br>          &lt;h2&gt;{post.title}&lt;/h2&gt;<br>          &lt;p&gt;{post.description}&lt;/p&gt;<br>        &lt;/div&gt;<br>      ))}<br>    &lt;/main&gt;<br>  );<br>}<br><br>export default App;</pre><h4>👉 useContext</h4><p>Let’s talk about this built-in state management in React, <strong>useContext</strong>. It is designed for sharing state between components without props drilling, but ideal for a simple global states eg. toggle theme. Given the example below for <strong>useContext</strong>, we need to</p><ul><li>Describe the shape of the context like what we do for the component, eg. <strong>ThemeContextState</strong>.</li><li>Define the <strong>createContext&lt;T&gt;(T)</strong>. It is a good practice to provide a <strong>null </strong>default, it will get <strong>null </strong>if a component uses the context without a provider.</li><li>Create a custom hook for the <strong>useContext</strong>, eg. <strong>useThemeContext</strong>, it allows components to access the theme and its function.</li><li>Define the <strong>children </strong>prop for the context provider.</li><li>Define the component for the context provider, eg. <strong>ThemeContextProvider</strong>.</li><li>Make sure to wrap the context provider in App.tsx.</li></ul><pre>// theme-context.tsx<br>import { createContext, useContext, useState, type ReactNode } from &quot;react&quot;;<br><br>export type Theme = &quot;light&quot; | &quot;dark&quot;;<br><br>// Define the type of ThemeContext state<br>type ThemeContextState = {<br>  theme: Theme;             <br>  toggleTheme: () =&gt; void; <br>};<br><br>// Create the context with a default value of null<br>const ThemeContext = createContext&lt;ThemeContextState | null&gt;(null);<br><br>// Custom hook to access ThemeContext<br>export function useThemeContext() {<br>  const themeContext = useContext(ThemeContext);<br><br>  if (themeContext === null) {<br>    throw new Error(&#39;useThemeContext must be used within a ThemeContextProvider&#39;);<br>  }<br><br>  return themeContext;<br>}<br><br>type ThemeContextProviderProps = {<br>  children: ReactNode;<br>};<br><br>export function ThemeContextProvider({ children }: ThemeContextProviderProps) {<br>  const [theme, setTheme] = useState&lt;Theme&gt;(&quot;light&quot;);<br><br>  const toggleTheme = () =&gt; {<br>    setTheme((prevTheme) =&gt; (prevTheme === &quot;light&quot; ? &quot;dark&quot; : &quot;light&quot;));<br>  };<br><br>  const contextValue: ThemeContextState = {<br>    theme,<br>    toggleTheme,<br>  };<br><br>  return (<br>    &lt;ThemeContext.Provider value={contextValue}&gt;<br>      {children}<br>    &lt;/ThemeContext.Provider&gt;<br>  );<br>}</pre><p>The use case will be,</p><pre>// ToggleTheme.tsx<br>import { useThemeContext } from &#39;./ThemeContext&#39;;<br><br>const ToggleTheme = () {<br>  const { theme, toggleTheme } = useThemeContext();<br><br>  return (<br>    &lt;div&gt;<br>      &lt;p&gt;theme: {theme}&lt;/p&gt;<br>      &lt;button onClick={toggleTheme}&gt;Toggle Theme&lt;/button&gt;<br>    &lt;/div&gt;<br>  );<br>}<br><br>export default ToggleTheme;<br><br>// App.tsx<br>const App = () =&gt; {<br>  return (<br>    &lt;ThemeContextProvider&gt;<br>      &lt;/ToggleTheme&gt;<br>    &lt;/ThemeContextProvider&gt;<br>  );<br>}<br><br>export default App;</pre><h4>👉 Redux Toolkit (RTK)</h4><p>Redux toolkit (RTK), however it is a more robust solution for managing complex application states and ideal for large scale applications due to more structured and scalable.</p><p>First, let’s setup the <strong>store </strong>and <strong>slice</strong>. Given the example below for a to-do list.</p><pre>// todo-slice.ts<br>import { createSlice, type PayloadAction } from &quot;@reduxjs/toolkit&quot;;<br><br>export type Todo = {<br>  id: string;<br>  task: string;<br>};<br><br>type TodoState = {<br>  todos: Todo[];<br>};<br><br>const initialState: TodoState = {<br>  todos: [],<br>};<br><br>export const todoSlice = createSlice({<br>  name: &quot;todos&quot;,<br>  initialState,<br>  reducers: {<br>    addTodo: (state, action: PayloadAction&lt;{ id: string; task: string }&gt;) =&gt; {<br>      state.todos.push({ ...action.payload, completed: false });<br>    },<br>    removeTodo: (state, action: PayloadAction&lt;string&gt;) =&gt; {<br>      state.todos = state.todos.filter((todo) =&gt; todo.id !== action.payload);<br>    },<br>  },<br>});<br><br>export const { addTodo, removeTodo } = todoSlice.actions;</pre><p>In todo-slice.ts, the initial state and two reducers are defined. <strong>PayloadAction </strong>is used to define the shape of actions in slice when we want to dispatch actions that carry data (payload).</p><pre>// store.ts<br>import { configureStore } from &quot;@reduxjs/toolkit&quot;;<br>import { todoSlice } from &quot;./todo-slice&quot;;<br><br>export const store = configureStore({<br>  reducer: {<br>    todos: todoSlice.reducer,<br>  },<br>});<br><br>export type RootState = ReturnType&lt;typeof store.getState&gt;;<br>export type AppDispatch = typeof store.dispatch;</pre><p>In store.ts, first setup the store using <strong>configureStore</strong>. The <strong>RootState </strong>and <strong>AppDispatch</strong> are exported for the use when defining the type of state and dispatch in hooks.ts.</p><p>Next, create another file named hooks.ts to create custom hooks for the slice, this is because they do not automatically infer the types for the selector and dispatch. Besides, we would not need to repeat this type casting anymore when using <strong>useDispatch</strong> and <strong>useSelector</strong> in each component.</p><pre>// hooks.ts<br>import { useDispatch, useSelector, type TypedUseSelectorHook } from &quot;react-redux&quot;;<br>import { AppDispatch, RootState } from &quot;./store&quot;;<br><br>// Custom hooks for dispatch and selector<br>export const useToDoDispatch = () =&gt; useDispatch&lt;AppDispatch&gt;();<br>export const useToDoSelector: TypedUseSelectorHook&lt;RootState&gt; = useSelector;</pre><p>In hooks.ts, import both the <strong>AppDispatch</strong> and <strong>RootState</strong> from store.ts, and define <strong>useToDoDispatch</strong> to provide <strong>useDispatch</strong> function with the type <strong>AppDispatch</strong>.</p><p>The <strong>useToDoSelector</strong> wraps <strong>useSelector</strong> and provides the correct typing via <strong>TypedUseSelectorHook&lt;RootState&gt;</strong> to ensure the selector works with the correct root state type.</p><p>Now, they will be correctly typed when using <strong>useToDoDispatch</strong> and in <strong>useToDoSelector</strong> in each component, as below.</p><pre>// ToDo.tsx <br>import React, { useState } from &quot;react&quot;;<br>import { useToDoDispatch, useToDoSelector } from &quot;../store/hooks&quot;;<br>import { addTodo, removeTodo } from &quot;../store/todo-slice&quot;;<br><br>const Todo = () =&gt; {<br>  const [task, setTask] = useState(&quot;&quot;);<br>  const todos = useToDoSelector(state =&gt; state.todos.todos);<br>  const dispatch = useToDoDispatch();<br><br>  const handleAddToDo = () =&gt; {<br>    const newTodo = {<br>      id: 1,<br>      task,<br>    };<br>    dispatch(addTodo(newTodo));<br>    setTask(&quot;&quot;);<br>  };<br><br>  return (<br>    &lt;div&gt;<br>      &lt;h1&gt;To Do List&lt;/h1&gt;<br>      &lt;input<br>        value={task}<br>        onChange={(e) =&gt; setTask(e.target.value)}<br>        placeholder=&quot;Enter task&quot;<br>      /&gt;<br>      &lt;button onClick={handleAddToDo}&gt;Add Task&lt;/button&gt;<br><br>      &lt;ul&gt;<br>        {todos.map((todo) =&gt; (<br>          &lt;li key={todo.id}&gt;<br>            {todo.task}<br>            &lt;button onClick={() =&gt; dispatch(removeTodo(todo.id))}&gt;Remove&lt;/button&gt;<br>          &lt;/li&gt;<br>        ))}<br>      &lt;/ul&gt;<br>    &lt;/div&gt;<br>  );<br>}<br><br>export default Todo;</pre><p>That covers the essentials of React with TypeScript, we can now work with it confidently. ☘️</p><p>Using React with TypeScript is strongly recommended because it is a best practice that ensures strong<strong> type safety</strong>, leading to <strong>fewer to no runtime errors</strong> and <strong>improve code reliability.</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bae53ef4e26d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[React + TypeScript — Part 1]]></title>
            <link>https://medium.com/@mun1013/react-typescript-part-1-94d5da740c2d?source=rss-4e6df3e6ef0c------2</link>
            <guid isPermaLink="false">https://medium.com/p/94d5da740c2d</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[frontend-development]]></category>
            <category><![CDATA[react-typescript]]></category>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[kahmun]]></dc:creator>
            <pubDate>Fri, 06 Sep 2024 04:10:21 GMT</pubDate>
            <atom:updated>2024-09-14T08:05:17.880Z</atom:updated>
            <content:encoded><![CDATA[<h3>React + TypeScript — Part 1</h3><p>In this post, let’s dive into the essentials of using TypeScript with React, exploring how it can streamline our development process, reduce bugs, and make our codebase easier to manage.</p><p>Just get started with this tool — <strong>Vite</strong>, execute a single command npm create vite@latest sample-project, select <strong>React </strong>as a framework and select <strong>TypeScript</strong> as a variant, and press the <strong>Enter </strong>key. Then, we will have a fully configured development environment, including a ready-to-use tsconfig.json file.</p><p>We don’t need to understand every configuration option in tsconfig.json for most use cases in a React TypeScript project, but it is important to understand a few commonly used options such as:</p><ul><li><strong>target: </strong>Specifies the JavaScript version eg. ES6 or ESNext.</li><li><strong>module</strong>: Defines the module code generation method eg.ESNext or CommonJS.</li><li><strong>strict</strong>: Enables strict type-checking.</li><li><strong>jsx</strong>: Set to react-jsx for React projects using JSX.</li><li><strong>include</strong>: Specifies the files or directories to include in the compilation, eg. [&quot;src&quot;].</li><li><strong>exclude</strong>: Specifies the files or directories to exclude from compilation, eg. node_modules or dist.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Zk8l7HQT9VJCc3jh32qvSA.png" /></figure><h4>👉 Type Alias For A React Component</h4><pre>type ToDoProps = {<br>  title: string; <br>  description: string;<br>  onDelete: (id: number) =&gt; void;<br>};<br><br>const ToDo = ({<br>  title, <br>  description,<br>  onDelete<br>}: ToDoProps) =&gt; {<br>  return (<br>    &lt;article&gt;<br>      &lt;div&gt;<br>        &lt;h2&gt;{title}&lt;/h2&gt;<br>        &lt;p&gt;{description}&lt;/p&gt;<br>      &lt;/div&gt;<br>      &lt;button onClick={() =&gt; onDelete(id)}&gt;Delete&lt;/button&gt;<br>    &lt;/article&gt;<br>  )<br>}<br><br>export default ToDo;<br><br>// Alternatively (for personal preference)<br>const ToDo: React.FC&lt;ToDoProps&gt; = ({<br>  title, <br>  description,<br>  onDelete<br>}) =&gt; {<br>  return ...<br>}<br><br>export default ToDo;</pre><h4>👉 <strong>Defining Type For A Children Prop</strong></h4><p>In this case<strong>, </strong>ReactNode<strong> </strong>is used for the children prop to indicate that any valid React elements can be passed as a child to the component.</p><pre>import { type ReactNode } from &quot;react&quot;;<br><br>type ToDoProps = {<br>  title: string; <br>  children: ReactNode;<br>  onDelete: (id: number) =&gt; void;<br>};<br><br>const ToDo = ({<br>  title, <br>  children,<br>  onDelete<br>}: ToDoProps) =&gt; {<br>  return (<br>    &lt;article&gt;<br>      &lt;div&gt;<br>        &lt;h2&gt;{title}&lt;/h2&gt;<br>        {children}<br>      &lt;/div&gt;<br>      &lt;button onClick={() =&gt; onDelete(id)}&gt;Delete&lt;/button&gt;<br>    &lt;/article&gt;<br>  )<br>}<br><br>export default ToDo;</pre><p>Alternatively, we can use PropsWithChildren as well. It will give us a prop object that has this children key, as below.</p><pre>import { type PropsWithChildren } from &quot;react&quot;;<br><br>type ToDoProps = PropsWithChildren&lt;{ <br>  title: string;<br>  onDelete: (id: number) =&gt; void;<br>}&gt;;</pre><h4>👉 Key Prop</h4><p>The key prop is a unique identifier that React uses to manage and update a single element within a list. The good news is we can omit it in the props type.</p><pre>// ToDo.tsx<br>type ToDoProps = {<br>  title: string; <br>};<br><br>const ToDo = ({ title }: ToDoProps) =&gt; {<br>   return &lt;li&gt;{title}&lt;/li&gt;;<br>}<br><br>// ToDoList.tsx<br>const ToDoList = () =&gt; {<br>  const todo = [{ title: &#39;working&#39; }, { title: &#39;cooking&#39; }];<br><br>  return (<br>    &lt;&gt;<br>      &lt;ul&gt;<br>         {todo.map((todo, index) =&gt; (<br>           &lt;ToDo key={todo} title={todo.title} /&gt;<br>         ))}<br>      &lt;/ul&gt;<br>    &lt;/&gt;<br>  )<br>}<br><br>export default ToDoList;</pre><h4>👉 useState</h4><p>useState&lt;T&gt;(T) is the typing for the useState hook, where T represents the type of the state value, eg. boolean, number, string, array, or object, as below.</p><pre>// able to import and expo<br>export type ToDoProps = {<br>  id: string;<br>  title: string;<br>  description: string;<br>}<br><br>// ToDoList.tsx<br>const ToDoList = () =&gt; {<br>  const [todo, setTodo] = useState&lt;ToDoProps[]&gt;([])<br><br>  return (<br>    &lt;&gt;<br>      &lt;ul&gt;<br>         //TS is able to infer the type of todo as the type of todo is defined.<br>         {todo.map((todo) =&gt; (<br>           &lt;ToDo key={todo} title={todo.title} /&gt;<br>         ))}<br>      &lt;/ul&gt;<br>    &lt;/&gt;<br>  )<br>}<br><br>export default ToDoList;</pre><h4>👉 useRef</h4><p>useRef&lt;T&gt;() is the typing for the useRef hook, where T represents the DOM element types in HTML where the ref will hold a reference to it. In the example below, HTMLInputElement will reference an input DOM element. The <strong>null </strong>value indicates that the reference is initially not pointing to any DOM element.</p><p>Use exclamation (!) mark to tell TypeScript that the value will not be <strong>null</strong>.</p><pre>const todo = useRef&lt;HTMLInputElement&gt;(null);<br>const enteredTodo = todo.current!.value;</pre><p>Here are some of the common options:</p><ul><li><strong>HTMLDivElement</strong>: For &lt;div&gt; elements.</li><li><strong>HTMLButtonElement</strong>: For &lt;button&gt; elements.</li><li><strong>HTMLAnchorElement</strong>: For &lt;a&gt; elements.</li><li><strong>HTMLFormElement</strong>: For &lt;form&gt; elements.</li></ul><h4>👉 Events</h4><p>When working with <strong>FormEvent</strong>, the generic form FormEvent&lt;T&gt; is used where T represents the DOM element types in HTML. If <strong>FormEvent </strong>is specified without the element type, it would show underline errors.</p><pre>import { FormEvent } from &#39;react&#39;;<br><br>const NewToDo = () =&gt; {<br>  const handleSubmit = (event: FormEvent&lt;HTMLFormElement&gt;) =&gt; {<br>    event.preventDefault();<br>    new FormData(event.currentTarget);<br>  };<br><br>  return (<br>    &lt;form onSubmit={handleSubmit}&gt;<br>      &lt;input type=&quot;text&quot; name=&quot;name&quot; /&gt;<br>      &lt;button type=&quot;submit&quot;&gt;Submit&lt;/button&gt;<br>    &lt;/form&gt;<br>  );<br>};<br><br>export default NewToDo;</pre><h4>👉 Dynamic Component With Required Props</h4><p>It is a good practice to create reusable and dynamic components in our React project. This example showcases a flexible component where each mode can have its own required props.</p><pre>import { type ReactNode } from &quot;react&quot;;<br><br>// Define prop types for different modes<br>type SuccessNotificationProps = {<br>  type: &#39;success&#39;;<br>  message: string;<br>  children: ReactNode;<br>};<br><br>type ErrorNotificationProps = {<br>  type: &#39;error&#39;;<br>  errorCode?: number;<br>  message: string;<br>  children: ReactNode;<br>};<br><br><br>// Union of all prop types<br>type NotificationProps = SuccessNotificationProps | ErrorNotificationProps;<br><br>const Notification = (props: NotificationProps) =&gt; {<br>  if (props.type === &#39;success&#39;) {<br>    return (<br>      &lt;div className=&quot;notification-success&quot;&gt;<br>        {props.message}<br>        {props.children}<br>      &lt;/div&gt;<br>    );<br>  }<br><br>  if (props.type === &#39;error&#39;) {<br>    return (<br>      &lt;div className=&quot;notification-error&quot;&gt;<br>        &lt;b&gt;Error Code: {props.errorCode ?? &#39;Unknown&#39;}&lt;/b&gt;<br>        {props.message}<br>        {props.children}<br>      &lt;/div&gt;<br>    );<br>  }<br><br>  return null;<br>}<br><br>export default Notification;</pre><h4>👉 <strong>Wrapper Component</strong></h4><p>Both ComponentPropsWithoutRef and ComponentPropsWithRef are used when creating wrapper components in React, with or without ref prop.</p><p>With ComponentPropsWithoutRef:</p><pre>import { type ComponentPropsWithoutRef } from &quot;react&quot;;<br><br>type InputProps = {<br>  id: string;<br>  label: string;<br>} &amp; ComponentPropsWithoutRef&lt;&#39;input&#39;&gt;;<br><br>const Input = ({ id, label, ...props }: InputProps ) =&gt; {<br>  return (<br>    &lt;p&gt;<br>      &lt;label htmlFor={id}&gt;{label}&lt;/label&gt;<br>      &lt;input id={id} name={id} {...props} /&gt;<br>    &lt;/p&gt;<br>  );<br>};<br><br>export default Input;</pre><p>With ComponentPropsWithRef:</p><pre>import { type ComponentPropsWithoutRef, forwardRef } from &quot;react&quot;;<br><br>type InputProps = {<br>  id: string;<br>  label: string;<br>} &amp; ComponentPropsWithoutRef&lt;&#39;input&#39;&gt;;<br><br>const Input = forwardRef&lt;HTMLInputElement, InputProps&gt;(function Input(<br>  { id, label, ...props },<br>  ref<br>) {<br>  return (<br>    &lt;p&gt;<br>      &lt;label htmlFor={id}&gt;{label}&lt;/label&gt;<br>      &lt;input id={id} name={id} {...props} ref={ref}/&gt;<br>    &lt;/p&gt;<br>  );<br>});<br><br>export default Input;</pre><p>🍭<strong>[As of April 2024] </strong>In React 19, we can now access ref as a prop for function components without using forwardRef<strong>. </strong>Refer to this <a href="https://react.dev/blog/2024/04/25/react-19">link</a>.</p><p>Alternatively, instead of using ComponentPropsWithRef , we can use RefObject.</p><pre>import { RefObject } from &quot;react&quot;;<br><br>type InputProps = {<br>  id: string;<br>  label: string;<br>  ref: RefObject&lt;HTMLInputElement&gt;;<br>}<br><br>// without using forwardRef<br>const Input = ({ id, label, ref, ...props }: InputProps ) =&gt; {<br>  return (<br>    &lt;p&gt;<br>      &lt;label htmlFor={id}&gt;{label}&lt;/label&gt;<br>      &lt;input id={id} name={id} {...props} ref={ref}/&gt;<br>    &lt;/p&gt;<br>  );<br>};<br><br>export default Input;</pre><p>Besides, we can build a wrapper component that renders different elements as well.</p><pre>type ButtonProps = {<br>  type: &#39;button&#39;;<br>} &amp; ComponentPropsWithoutRef&lt;&#39;button&#39;&gt;;<br><br>type AnchorProps = {<br>  type: &#39;anchor&#39;<br>} &amp; ComponentPropsWithoutRef&lt;&#39;a&#39;&gt;;<br><br>const Button = (props: ButtonProps | AnchorProps) =&gt; {<br>  if (props.type === &#39;anchor&#39;) {<br>    return &lt;a {...props}&gt;&lt;/a&gt;<br>  }<br><br>  return &lt;button {...props}&gt;&lt;/button&gt;;<br>}</pre><h4>👉 Polymorphic Component</h4><p>Polymorphic component is so <strong>sweet </strong>that it allows us to <strong>reuse </strong>a single component and turn into any component without rewriting the logic.</p><p>For example, instead of creating multiple components for different elements eg. Button and Link. We can create a single component that adapts its behavior and props based on the as prop.</p><p>Moreover, it promotes<strong> type safety</strong>⛑️! ComponentPropsWithoutRef ensures that TypeScript knows which props are valid for the element you’re rendering. It will throw errors if you pass invalid props into it.</p><pre>// Container.tsx<br>import {<br>  type ReactNode,<br>  type ElementType,<br>  type ComponentPropsWithoutRef,<br>} from &quot;react&quot;;<br><br>type ContainerProps&lt;T extends ElementType&gt; = {<br>  as?: T;<br>  children: ReactNode;<br>} &amp; ComponentPropsWithoutRef&lt;T&gt;;<br><br>const Container = &lt;C extends ElementType&gt; ({<br>  as,<br>  children,<br>  ...props<br>}: ContainerProps&lt;C&gt;) =&gt; {<br>  const Component = as || &quot;div&quot;;<br><br>  return &lt;Component {...props}&gt;{children}&lt;/Component&gt;;<br>}<br><br>export default Container;<br><br>// use case<br>// App.tsx<br>const App = () =&gt; {<br>  return (<br>    &lt;div&gt;<br>      &lt;Container as=&quot;a&quot; href=&quot;https://abc.com&quot;&gt;<br>        Link<br>      &lt;/Container&gt;<br><br>      &lt;Container as=&quot;button&quot; onClick={() =&gt; alert(&#39;Button clicked!&#39;)}&gt;<br>        Button<br>      &lt;/Container&gt;<br>    &lt;/div&gt;<br>  );<br>}<br><br>export default App;</pre><p>Let’s dive further in the next post.</p><p><a href="https://medium.com/@mun1013/react-typescript-part-2-bae53ef4e26d">React + TypeScript — Part 2</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=94d5da740c2d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Guide to migrating from Create React App (CRA) to Vite]]></title>
            <link>https://medium.com/@mun1013/guide-to-migrating-from-create-react-app-cra-to-vite-5516f55aa410?source=rss-4e6df3e6ef0c------2</link>
            <guid isPermaLink="false">https://medium.com/p/5516f55aa410</guid>
            <category><![CDATA[create-react-app]]></category>
            <category><![CDATA[software-maintenance]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[reactjs]]></category>
            <category><![CDATA[vitejs]]></category>
            <dc:creator><![CDATA[kahmun]]></dc:creator>
            <pubDate>Sat, 22 Jun 2024 05:36:55 GMT</pubDate>
            <atom:updated>2024-06-22T05:36:55.964Z</atom:updated>
            <content:encoded><![CDATA[<p>Lately, I was notified by the security team within my company to resolve all the vulnerabilities found in our web application as soon as possible.</p><p>When I opened the Synk report, I saw a long list of vulnerabilities ranging from medium to high severity related to react-scripts package. There is a need to upgrade its dependencies as well. Our web application is using the latest react-scripts version which is 5.0.1 from two years ago and it is no longer maintainable.</p><p>So, instead of overriding dependency version, <strong>Vite</strong> came to mind!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*5eD-dt8JWkFYTNt8fvSYlQ.png" /></figure><p>Here’s a step-by-step guide I took to make the switch from CRA to Vite in our web application.</p><h4><strong>1. Install dependencies </strong>⚡️</h4><p>First and foremost, you will need to install several dependencies.</p><pre>npm install vite @vitejs/plugin-react vite-tsconfig-paths vite-plugin-svgr vite-plugin-commonjs --save-dev</pre><ul><li>vite</li><li>@vitejs/plugin-react</li><li>vite-tsconfig-paths</li></ul><blockquote>Optional dependencies:</blockquote><ul><li>vite-plugin-svgr</li><li>vite-plugin-commonjs</li></ul><h4><strong>2. Create vite.config.ts </strong>⚡ ️</h4><p>Create a file named vite.config.ts in the root of your project. This is used to control various aspects of how Vite operates in your project.</p><blockquote>Some common configurations</blockquote><pre>import path from &#39;path&#39;;<br>import { defineConfig } from &#39;vite&#39;;<br>import react from &#39;@vitejs/plugin-react&#39;;<br><br>export default defineConfig({<br>  base: &#39;./&#39;,<br>  plugins: [<br>    react(),<br>  ],<br>  server: {<br>    open: true, // automatically open the app in the browser<br>    port: 3000,<br>  },<br>  resolve: {<br>    alias: {<br>      screens: path.resolve(__dirname, &#39;./src/screens&#39;),<br>    },<br>  },<br>  build: {<br>    outDir: &#39;build&#39;,<br>  },<br>});</pre><p>Let’s go through each configuration option:</p><ul><li><strong>base</strong>: This sets the base URL for your application. If your application is deployed at https://abc.com/portal/, you should set base: &#39;/portal/&#39;.</li><li><strong>plugin</strong>: This is to add any Vite’s plugins to your application. The React plugin from @vitejs/plugin-react is necessary to handle JSX and other React specific features. Other optional plugins such as commonjs (to convert CommonJS module into ES6 module if needed), svgr (if there is SVGs in your application, you will need to import it directly as React component) and vite-tsconfig-paths is used to resolve TypeScript path aliases.</li></ul><blockquote>Other plugins:</blockquote><pre>// vite.config.ts<br>import { defineConfig, transformWithEsbuild } from &#39;vite&#39;;<br>import react from &#39;@vitejs/plugin-react&#39;;<br>import commonjs from &#39;vite-plugin-commonjs&#39;;<br>import svgr from &#39;vite-plugin-svgr&#39;;<br>import vitetsConfigPaths from &#39;vite-tsconfig-paths&#39;;<br><br>export default defineConfig({<br>  plugins: [<br>    react(),<br>    vitetsConfigPaths(),<br>    commonjs(),<br>    svgr({<br>      include: [<br>        &#39;src/**/*.svg&#39;,<br>      ],<br>    }),<br>  ],<br>});<br><br>………………………………………………………………………………………………………………………………………………………………<br><br>// We need to import SVG files as React component, as below:<br>// Component.jsx<br>import Icon from &#39;./icon.svg?react&#39;.<br><br>………………………………………………………………………………………………………………………………………………………………<br><br>// tsconfig.json<br>{<br>  &quot;compilerOptions&quot;: {<br>    &quot;paths&quot;: {<br>      &quot;components/*&quot;: [&quot;src/components/*&quot;],<br>    }<br>  }<br>}<br><br>// Instead of importing modules using relative paths<br>import Button from &#39;../../components/Button&#39;;<br><br>// You can use defined aliases<br>import Button from &#39;components/Button&#39;;</pre><ul><li><strong>server</strong>: This is to configure the port number for your development server. Default is port 5173.</li><li><strong>resolve</strong>: This is to simplify the import paths using aliases.</li><li><strong>build</strong>: This is to customise the build process in Vite, eg. the name of output directory, if you want to maintain the same build folder as CRA, use build, the default is dist. Besides, you can configure code splitting as well.</li></ul><blockquote>Optional configurations</blockquote><pre>import { defineConfig } from &#39;vite&#39;;<br><br>export default defineConfig({<br>  optimizeDeps: {<br>    force: true,<br>    esbuildOptions: {<br>      loader: {<br>        &#39;.js&#39;: &#39;jsx&#39;,<br>      },<br>    },<br>  },<br>});</pre><ul><li><strong>OptimizeDeps</strong>: This is to configure the pre-bundling for dependencies using esbuild (Vite’s default bundler). By setting force: true forces Vite to pre-bundle the dependencies on every development startup to ensure all dependencies are always up-to-date. Besides, loader: { &#39;.js&#39;: &#39;jsx&#39; } specifies the JS files should be treated as JSX files by ESBuild. This is useful when your JS files contain JSX syntax.</li></ul><h4><strong>3. Create vite-env.d.ts file </strong>⚡️</h4><p>Create a file named <a href="https://vitejs.dev/guide/features.html#client-types">vite-env.d.ts</a> in the root of your project.</p><pre>// vite-env.d.ts<br>/// &lt;reference types=&quot;vite/client&quot; /&gt;</pre><p>This line includes type definition for Vite’s global variables and client specific features. This file also can be used for custom typings and module declarations that help TypeScript understand how to handle other assets and global variables in your Vite project.</p><h4><strong>4. Update index.html </strong>⚡️</h4><ul><li>Move the index.html file from the public folder to the root. In CRA, index.html should be found in the public folder. Vite, however, expects this file in the root of your project.</li><li>Remove %PUBLIC_URL%<em>. </em>Vite handles static assets and public paths differently and it allows you to import assets directly in your JavaScript files or use relative paths in your HTML.</li></ul><blockquote>CRA’s index.html</blockquote><pre>&lt;!DOCTYPE html&gt;<br>&lt;html lang=&quot;en&quot;&gt;<br>&lt;head&gt;<br>  &lt;meta name=&quot;robots&quot; content=&quot;noindex,nofollow&quot; /&gt;<br>  &lt;meta charset=&quot;utf-8&quot; /&gt;<br>  &lt;link rel=&quot;icon&quot; href=&quot;%PUBLIC_URL%/favicon.png&quot; /&gt;<br>  &lt;link rel=&quot;manifest&quot; href=&quot;%PUBLIC_URL%/manifest.json&quot; /&gt;<br>  &lt;title&gt;CRA&lt;/title&gt;<br>&lt;/head&gt;<br><br>&lt;body&gt;<br>  &lt;noscript&gt;You need to enable JavaScript to run this app.&lt;/noscript&gt;<br>  &lt;div id=&quot;root&quot;&gt;&lt;/div&gt;<br>  &lt;script src=&quot;%PUBLIC_URL%/src/main.jsx&quot;&gt;&lt;/script&gt;<br>&lt;/body&gt;<br>&lt;/html&gt;</pre><blockquote>Vite’s index.html</blockquote><pre>&lt;!DOCTYPE html&gt;<br>&lt;html lang=&quot;en&quot;&gt;<br>&lt;head&gt;<br>  &lt;meta name=&quot;robots&quot; content=&quot;noindex,nofollow&quot; /&gt;<br>  &lt;meta charset=&quot;utf-8&quot; /&gt;<br>  &lt;link rel=&quot;icon&quot; href=&quot;/favicon.png&quot; /&gt;<br>  &lt;link rel=&quot;manifest&quot; href=&quot;/manifest.json&quot; /&gt;<br>  &lt;title&gt;CRA&lt;/title&gt;<br>&lt;/head&gt;<br><br>&lt;body&gt;<br>  &lt;noscript&gt;You need to enable JavaScript to run this app.&lt;/noscript&gt;<br>  &lt;div id=&quot;root&quot;&gt;&lt;/div&gt;<br>  &lt;script src=&quot;/src/main.jsx&quot;&gt;&lt;/script&gt;<br>&lt;/body&gt;<br>&lt;/html&gt;</pre><h4><strong>5. Update tsconfig.json </strong>⚡️</h4><p>You need to update tsconfig.json specifically for target, types and lib.</p><pre>{<br>  &quot;compilerOptions&quot;: {<br>    &quot;target&quot;: &quot;ESNext&quot;,<br>    &quot;types&quot;: [&quot;vite/client&quot;, &quot;vite-plugin-svgr/client&quot;]<br>    &quot;lib&quot;: [&quot;dom&quot;, &quot;dom.iterable&quot;, &quot;esnext&quot;],<br>    &quot;allowJs&quot;: true,<br>    &quot;skipLibCheck&quot;: true,<br>    &quot;esModuleInterop&quot;: true,<br>    &quot;allowSyntheticDefaultImports&quot;: true,<br>    &quot;strict&quot;: true,<br>    &quot;forceConsistentCasingInFileNames&quot;: true,<br>    &quot;module&quot;: &quot;esnext&quot;,<br>    &quot;moduleResolution&quot;: &quot;node&quot;,<br>    &quot;resolveJsonModule&quot;: true,<br>    &quot;isolatedModules&quot;: true,<br>    &quot;noEmit&quot;: true,<br>    &quot;noFallthroughCasesInSwitch&quot;: true,<br>    &quot;allowImportingTsExtensions&quot;: true,<br>    &quot;jsx&quot;: &quot;react-jsx&quot;,<br>  },<br>  &quot;exclude&quot;: [<br>    &quot;node_modules&quot;<br>  ],<br>}</pre><h4><strong>6. Environment variables </strong>⚡️</h4><p>It’s required to migrate all the environment variables from process.env.REACT_APP_ to import.meta.env.VITE_ in your Vite project. In Vite, it uses import.meta.env to access the environment variable and it must start with the prefix <strong>VITE_</strong>.</p><pre>// CRA<br>process.env.REACT_APP_API<br><br>// Vite<br>import.meta.env.VITE_API<br><br>console.log(import.meta.env) <br>// { BASE_URL: &#39;/&#39;, DEV: true, MODE: &#39;development&#39;, PROD: false, SSR: false }</pre><p>There are several pre-defined environment variables in import.meta.env such as BASE_URL, DEV, MODE, PROD and SSR. Vite automatically sets import.meta.env.MODE to development when you run <strong>vite</strong>, and sets to production when you run <strong>vite build</strong>. Besides, you can specify the mode when running Vite commands based on your needs, eg. vite build --mode staging.</p><h4><strong>7. Uninstall react-scripts </strong>⚡️</h4><p>Simply uninstall react-scripts since we have replaced with Vite and proceed to delete craco.config.js or config-overrides.js if there is any.</p><pre>npm uninstall react-scripts</pre><h4><strong>8. Update scripts in package.json </strong>⚡️</h4><p>After removing react-scripts package, you need to update the scripts to use vite.</p><pre>&quot;scripts&quot;: {<br>  &quot;start&quot;: &quot;vite&quot;,<br>  &quot;build&quot;: &quot;vite build&quot;,<br>  &quot;serve&quot;: &quot;vite preview&quot;<br>},</pre><h4><strong>9. Run the application </strong>⚡️</h4><p>Run the application with npm start. You should see your application open up in the browser instantly!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Xf80SpHvOUiJPX1jyIu7uQ.png" /><figcaption>Vite development server</figcaption></figure><p>You can also serve the static build of your application by running npm run build and then npx serve -s build to test the production build locally. 😋</p><h4><strong>10. ESLint &amp; Prettier setup </strong>⚡️</h4><p>Both CRA and Vite can use the same ESLint and Prettier configurations and there should be little to no migration needed. For my case, it returns an error when running eslint, which is <strong>Failed to load config “react-app” to extend from </strong>and it can be solved by installing the following package.</p><pre>npm install eslint-config-react-app</pre><h4>Errors &amp; Troubleshooting 🔧</h4><p>Here are some errors I encountered when migrating to Vite and the troubleshooting steps I took.</p><blockquote><strong>Failed to parse source for import analysis because the content contains invalid JS syntax. If you are using JSX, make sure to name the file with the .jsx or .tsx extension.</strong></blockquote><p>🔗 <a href="https://stackoverflow.com/a/76726872">Solution</a>: Change the file format from .js to .jsx and if it doesn’t work or there are a lot of affected files, just add a configuration in vite.config.js to treat JS files as JSX.</p><blockquote><strong>Uncaught SyntaxError: The requested module ‘/src/assets/images/logo.svg?import’ does not provide an export named ‘default’ (at NavBar.js:16:8)</strong></blockquote><p>🔗 <a href="https://github.com/pd4d10/vite-plugin-svgr/issues/117">Solution</a>: Replace with /src/assets/images/logo.svg?react<strong> </strong>to resolve it. You may need to add this <a href="https://www.npmjs.com/package/vite-plugin-svgr">plugin</a> into vite.config.js to transform SVGs into React components.</p><blockquote><strong>Uncaught ReferenceError: require is not defined</strong></blockquote><p>🔗 <a href="https://stackoverflow.com/a/78531730">Solution</a>: npm install vite-plugin-commonjs and add the plugin into vite.config.js will resolve it.</p><blockquote><strong>Uncaught ReferenceError: process is not defined</strong></blockquote><p>🔗 <a href="https://github.com/vitejs/vite/issues/1973">Solution</a>: Replace process.env with import.meta.env.</p><blockquote><strong>Failed to load module script: Expected a JavaScript module script but the server responded with a MIME type of “text/html”. Strict MIME type checking is enforced for module scripts per HTML spec.</strong></blockquote><p>🔗 <a href="https://stackoverflow.com/a/76991278">Solution</a>: I configure this <a href="https://stackoverflow.com/a/76991278">setup</a> and it works. Given if your application lives in a subdirectory.</p><h4>Conclusion</h4><p>After switching from CRA to Vite, the development process saw significant improvements in our web application.</p><ul><li><strong>Development server startup</strong>: The startup time decreased from roughly 14 seconds to just only 1 seconds.</li><li><strong>NPM install</strong>: the npm install process is noticeably faster, from 2 minutes to one and a half minutes.</li><li><strong>Build time</strong>: The build time was reduced from 45 seconds to 22 seconds.</li></ul><p>Overall, I am happy with the migration, it’s pretty straightforward yet bringing us a smoother development experience, to me it is a highly effective and effective alternative to CRA.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5516f55aa410" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[TypeScript Essentials & Key Concepts]]></title>
            <link>https://medium.com/aia-sg-techblog/typescript-essentials-key-concepts-64723477c65b?source=rss-4e6df3e6ef0c------2</link>
            <guid isPermaLink="false">https://medium.com/p/64723477c65b</guid>
            <category><![CDATA[typescript-generics]]></category>
            <category><![CDATA[typescript-tips]]></category>
            <category><![CDATA[typescript]]></category>
            <dc:creator><![CDATA[kahmun]]></dc:creator>
            <pubDate>Sun, 14 Apr 2024 15:33:23 GMT</pubDate>
            <atom:updated>2024-09-04T09:31:15.253Z</atom:updated>
            <content:encoded><![CDATA[<p>Dear readers, it’s been a while, but I am back!</p><p>Let’s talk about TypeScript.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/0*Zl1KDB8QpgKFWGKB.jpeg" /></figure><p>Nowadays Typescript has become increasingly popular for its type safety and scalability in the JavaScript development. Most important it could also catch potential errors in your code!</p><p>An important concept to highlight is that TypeScript code will be compiled into JavaScript code during the build process as TypeScript does not run in the browser.</p><p>There are two methods of installing TypeScript:</p><ol><li>Install locally in your project using the following command:</li></ol><pre>npm install typescript --save-dev<br><br>or<br><br>yarn add typescript --dev</pre><p>TypeScript is available as the package on the npm registry or yarn, then you can run the TypeScript compiler using the following command:</p><pre>npx tsc [file.ts]</pre><p>After running the command, TypeScript will compile file.ts into JavaScript file.js based on the TypeScript compiler&#39;s default settings or any custom settings defined in a tsconfig.json file.</p><p>2. Or, install globally on your system:</p><pre>npm install -g typescript</pre><p>By installing it globally, you can directly use the tsc command (without npx) in your terminal or command prompt to compile TypeScript into JavaScript file.</p><pre>tsc [file.ts]</pre><p>When you are writing TypeScript code, you will often encounter with various syntax features that you may not fully understand or that certain aspects feel strange <em>(Yeah that’s how I felt too)!</em></p><p>Before diving into primitive types and functions, let’s review some of these syntax and key concepts.</p><ol><li><strong>Type annotation ( : )</strong></li></ol><p>Type annotation :is primarily used when declaring variables, function arguments or function return types.</p><pre>let age: number = 10;<br>function greet(name: string): string {<br>  return `Hello, my name is ${name}.`;<br>}</pre><p><strong>2. Optional property ( ? )</strong></p><p>Optional property ? denotes an optional property in an object, it allows a property or parameter to be omitted when the corresponding field is not provided.</p><pre>type User = {<br>  name: string;<br>  age?: number; // optional property<br>}<br><br>function greet(user: User): string {<br>  if (user?.age !== undefined) {<br>    return `Hello, my name is ${name} and I am ${age} year old.`;<br>  }<br>  <br>  return `Hello, my name is ${name}`;<br>}</pre><p><strong>3. Non-null assertion ( ! )</strong></p><p>Non-null assertion ! is used to assert that the value is not null or undefined.</p><pre>function greet(name: User): string | null {<br>  if (name === &#39;kahmun&#39;) {<br>    return `Hello, my name is ${name}`;<br>  }<br>  return null;<br>}<br><br>let name = &#39;kahmun&#39;;<br>const greeting = greet(name)!; // assert that the return is not null</pre><p><strong>4. Type assertion ( as )</strong></p><p>Type assertion as is used to tell TypeScript to treat an expression as a specific type if it could not infer the type of the value.</p><pre>let name: any = &#39;kahmun&#39; // this variable might hold any type of value<br>let length = (name as string).length; // let TS know to treat it as string</pre><p><strong>5. Type union &amp; literal type ( | )</strong></p><p>Type union | allows you to specify that a variable can hold values of multiple different types.</p><pre>let a: string | number; // variable a can be either a string or a number<br>a = &#39;kahmun&#39;;<br>a = 12;</pre><p>While literal type | allows you to specify exact values that a variable can hold.</p><pre>let color: &#39;red&#39; | &#39;blue&#39; | &#39;green&#39;;<br><br>color = &#39;red&#39; // valid<br>color = &#39;black&#39; // Error: type &quot;black&quot; is not assignable</pre><p><strong>6. Type intersection ( &amp; )</strong></p><p>Type intersection &amp; is used to combine multiple types into a single type that has all the properties of each type.</p><pre>type Basic = {<br>  name: string;<br>  age: number;<br>}<br><br>type Contact - {<br>  mobile: string;<br>  homeAddress: string;<br>}<br><br>type User = Basic &amp; Contact;</pre><p><strong>7. Type generic ( &lt;T&gt; )</strong></p><p>Type genetic &lt;T&gt; allows you to define for reusable function or component that can work with any data type.</p><pre>// generic function to return array of any type<br>function arrayItem&lt;T&gt;(array: T[]): T[] {<br>    return array;<br>}<br><br>const colors: string[] = [&#39;red&#39;, &#39;blue&#39;, &#39;black&#39;];<br>const colorArray = arrayItem(colors);<br>..<br>const units: number[] = [1, 3, 4];<br>const unitArray = arrayItem(units);</pre><h3>Basic Primitive Types</h3><p>TypeScript supports the same primitive types like JavaScript such as string, boolean, number, null and undefined.</p><pre>// String<br>let name: string = &#39;kahmun&#39;;<br><br>// Boolean<br>let isDone: boolean = true;<br><br>// Number<br>let age: number = 22;<br>let decimal: number = 6.5;<br><br>// Null<br>let data: null = null;<br><br>// Undefined<br>let undefinedValue: undefined = undefined;</pre><h3>Object Type</h3><p>An object type is defined using curly braces {} to describe the properties.</p><pre>// Define an object type<br>type User = {<br>  name: string;<br>  age: number;<br>  email?: string; // optional property<br>};<br><br>// Usage of the User object type<br>let kahmun: User = {<br>  name: &#39;Kah Mun&#39;,<br>  age: 32,<br>  email: &#39;kahmun@gmail.com&#39;<br>};<br><br>let may: User = {<br>  name: &#39;May&#39;,<br>  age: 40,<br>}</pre><p>Another object type with nested properties.</p><pre>// Define an object type<br>type Contact = {<br>  mobile: string;<br>  homeAddress: string;<br>}<br><br>type User = {<br>  name: string;<br>  age: number;<br>  email?: string; // optional property<br>  contact: Contact // from Contact type<br>};<br><br>let kahmun: User = {<br>  name: &#39;Kah Mun&#39;,<br>  age: 32,<br>  contact: {<br>    mobile: &#39;+601234567&#39;,<br>    homeAddress: &#39;12, Home Street, 44000, Malaysia&#39;,<br>  }<br>}</pre><h3>Array Type</h3><p>TypeScript provides robust support for array, too. :D</p><pre>let colors: string[] = [&#39;red&#39;, &#39;blue&#39;, &#39;black&#39;];<br>let numbers: number[] = [1, 2, 3];<br>let mixedArray: (string | number)[] = [&#39;hi&#39;, &#39;I am&#39;, &#39;kahmun&#39;, 32];<br><br>type User = {<br>  name: string;<br>  age: number;<br>  email?: string; // optional property<br>};<br><br>let people: User[] = [<br>  {name: &#39;Kah Mun&#39;, age: 32},<br>  {name: &#39;May&#39;, age: 40},<br>];</pre><p>Or, read only array type to prevent further modification.</p><pre>let colors: readonly string[] = [&#39;red&#39;, &#39;blue&#39;, &#39;black&#39;];</pre><h3>Function Type</h3><pre>function add(a: number, b: number): number {<br>    return a + b;<br>}<br><br>// we can actually omit the return type as TS is able to infer it<br>function add(a: number, b: number) {<br>    return a + b;<br>}<br><br>// function with optional parameter<br>function add(a: number, b: number, c?: number) {<br>  if (c) { <br>    return a + b + c;<br>  }<br>  <br>  return a + b;<br>}</pre><h3>Type vs Interface</h3><p>In general, we can use whichever we prefer, we use type to define other type like object and function, but not when using interface. There are some key differences between type and interface, such as:</p><ol><li>interface is limited to define type for object <strong>only</strong>, while type can create aliases for any type, including object, function, intersection and union types, etc.</li><li>interface is able to extend another properties using the extends keyword. We can use interface when working on a project using class, but most of the time JavaScript doesn’t, therefore type is generally used.</li></ol><p>Example of <strong>type</strong>:</p><pre>// type definition for a function<br>type AddFunc: (a: number, b: number) =&gt; number;<br><br>// type alias<br>type Sum = {<br>  a: number;<br>  b: number:<br>  addFunc: AddFunc<br>}<br><br>let add: Sum = {<br>  a: 1,<br>  b: 2,<br>  addFunc: (a, b) =&gt; a + b<br>};<br><br>// merging type<br>type MultipleFunc: (c: number, d: number) =&gt; number;<br><br>type Mutiple = {<br>  c: number;<br>  d: number;<br>  multipleFunc: MultipleFunc<br>}<br><br>type Calculate = Sum &amp; Mutiple;<br><br>let calculate: Calculate = {<br>  a: 1,<br>  b: 2,<br>  addFunc: (a, b) =&gt; a + b,<br>  c: 2,<br>  d: 3,<br>  multipleFunc: (c, d) =&gt; c + d,<br>}</pre><p>Example of <strong>interface</strong>:</p><pre>// interface<br>interface Appearance {<br>  color: string;<br>  border: string;<br>}<br><br>// Interface for Reactangle extending the Shape interface<br>interface Rectangle extends Appearance {<br>  width: number;<br>  height: number;<br>}<br><br>function calculateArea(r: Rectangle): number {<br>   return r.width * r.height;<br>}<br><br>let myRectangle: Rectangle = {<br>    color: &#39;blue&#39;,<br>    border: &#39;5px&#39;<br>    width: 10,<br>    height: 5<br>};<br><br>const area = calculateArea(myRectangle);</pre><h3>Type Guard &amp; Type Narrowing</h3><p>These concepts allow you to narrow down the type of a variable within a certain code block to a more specific type.</p><p>Example of <strong>type guard:</strong></p><pre>function isString(value: any): string {<br>  return typeof value === &#39;string&#39;;<br>}<br><br>let a: any = &#39;hello world&#39;;<br><br>// execute a string method if x is a string<br>if (isString(a)) {<br>  console.log(x.toUpperCase());<br>} else {<br>  console.log(&#39;x is not a string&#39;);<br>}</pre><p>Example of <strong>type narrowing</strong>:</p><pre>function add(a: number | string, b: number | string) {<br>  if (typeof a === &#39;number&#39; &amp;&amp; typeof b === &#39;number&#39;) {<br>    return a + b;<br>  }<br>  <br>  return `${a} ${b}`;<br>}</pre><p>And with that, we’ve reached the end of our TypeScript’s <em>basic</em> adventure. Remember, writing TypeScript is like wearing a seatbelt on your code, whoops!</p><p>Until next time, happy TypeScript-ing! 😛</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=64723477c65b" width="1" height="1" alt=""><hr><p><a href="https://medium.com/aia-sg-techblog/typescript-essentials-key-concepts-64723477c65b">TypeScript Essentials &amp; Key Concepts</a> was originally published in <a href="https://medium.com/aia-sg-techblog">AIA Singapore Technology Blog</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Guide to React Native Testing Library]]></title>
            <link>https://medium.com/aia-sg-techblog/guide-to-react-native-testing-library-608feadc82df?source=rss-4e6df3e6ef0c------2</link>
            <guid isPermaLink="false">https://medium.com/p/608feadc82df</guid>
            <category><![CDATA[react-native]]></category>
            <category><![CDATA[react-testing-library]]></category>
            <dc:creator><![CDATA[kahmun]]></dc:creator>
            <pubDate>Thu, 22 Jun 2023 03:34:05 GMT</pubDate>
            <atom:updated>2023-06-22T03:34:05.825Z</atom:updated>
            <content:encoded><![CDATA[<p>Often, testing is part of the software development lifecycle. It is important for a several reasons:</p><ol><li>It helps to catch bugs before deploying to the production and prevent issues to end users.</li><li>It allows us to think carefully about the quality of the code.</li><li>It boosts our confidence that our code is worked as expected.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*aA3GxECQnD8xu2S5" /><figcaption>Photo by <a href="https://unsplash.com/@kellysikkema?utm_source=medium&amp;utm_medium=referral">Kelly Sikkema</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h4>Types of testing for front-end application 🧚‍♂️</h4><ol><li><strong>Unit testing</strong>: It typically focuses on verifying the code works correctly, such as providing inputs to a function and checking its output against expected results.</li><li><strong>Component testing</strong>: It focuses on verifying an individual component renders correctly and behaves as expected based on the provided inputs to it.</li><li><strong>Integration testing</strong>: It tests how multiple components interact with each other, generally involves rendering multiple components and requires external dependencies, services or APIs. It is required to mock these for tests.</li><li><strong>Snapshot testing</strong>: It captures a snapshot of the rendered output of a component and compares it to previous saved snapshot to detect visual changes. It should be used with in combination with unit and component testing to ensure comprehensive coverage of an application.</li><li><strong>End to end testing (E2E)</strong>: It typically verifies the entire application from start to end to ensure the user flows work correctly, this can include testing a user can sign up, login, perform activities, navigate to different pages and log out from an application.</li></ol><h4>Installing dependencies 🧚‍♂️</h4><p>React Native Testing Library is designed for testing React Native components, it has peerDependencies listing for react-test-renderer, hence we need to first install it.</p><pre>npm install --save-dev react-test-renderer</pre><p>Next, install React Native Testing Library.</p><pre>npm install --save-dev @testing-library/react-native</pre><p>There is a specific jest matcher for React native which is jest native library that provides additional matchers and utilities to test properties of React Native components.</p><pre>npm install --save-dev @testing-library/jest-native</pre><h4><a href="https://jestjs.io/docs/configuration/">Setting it up</a> 🧚‍♂️</h4><p>Usually creating a new React Native project will generate a default jest.config.js with some basic configuration. You can find it in the root directory of your project.</p><pre>{<br>  &quot;preset&quot;: &quot;jest-expo&quot;,<br>  &quot;setupFiles&quot;: [<br>     &#39;./src/mock/api&#39;,<br>     &#39;./src/mock/services&#39;,<br>  ],<br>  &quot;setupFilesAfterEnv&quot;: [&quot;@testing-library/jest-native/extend-expect&quot;],<br>  &quot;transformIgnorePatterns&quot;: [<br>    &quot;node_modules/(?!((jest-)?react-native|@react-native(-community)?)|expo(nent)?|@expo(nent)?/.*|@expo-google-fonts/.*|react-navigation|@react-navigation/.*)&quot;<br>  ],<br>  &quot;moduleFileExtensions&quot;: [<br>    &quot;ts&quot;,<br>    &quot;tsx&quot;,<br>    &quot;js&quot;,<br>    &quot;jsx&quot;,<br>  ],<br>  &quot;moduleNameMapper&quot;: &#39;^@/(.*)$&#39;: &#39;&lt;rootDir&gt;/src/$1&#39;,<br>}</pre><p>This is an example of the customize Jest’s configuration for React Native project based on our testing needs, which includes:</p><ol><li><strong>preset</strong>: jest-expo preset is used for testing React Native projects created using Expo, otherwise it would be react-native.</li><li><strong>setupFiles</strong>: This option is used to specify a module that should be executed before any tests run, such as setting up the test data or mocking external components, dependencies, services or APIs.</li><li><strong>setupFilesAfterEnv</strong>: This option is used to set up additional testing libraries such as @testing-library/jest-native.</li><li><strong>transformIgnorePatterns</strong>: This option is used to configure a list of file paths that should not be transformed, such as third party library files.</li><li><strong>moduleFileExtensions</strong>: This option is used to specify the file extensions that should be looked for when running tests.</li><li><strong>moduleNameMapper</strong>: This option is used to specify the mapped modules name with absolute or relative paths.</li></ol><p>Let’s take a look at the following commands to run a test file,</p><pre>// run a single test file<br>jest &lt;path-to-test-file&gt;<br><br>// run all test files in a folder<br>jest &lt;folder-path&gt;<br><br>// update snapshot<br>jest --updateSnapshot &lt;path-to-test-file&gt;</pre><h4>How to write test case for a component 🧚‍♂️</h4><p>A test suite is a collection of test cases that are designed to test a specific behavior of a system. But how do we write a test suite for a component that ends up an UI to end-users?</p><ol><li>Identify different states and behaviors of a component. This may include loading state, error state (when the data is not returned), or when the data is ready to be displayed on the UI. You may need to mock external services or APIs to retrieve the data.</li><li>Write test cases for each behaviors. Once you have identified different behaviors of the component, you can start writing test cases to verify the component is worked as expected. Take an example, you may need to verify that the loading screen is displayed once an user hits on a section, the data is correctly displayed after the loading, display an error message when the input is invalid, or successfully navigates to the next screen.</li><li>Run the tests and debug as needed once you have written your test cases. You can use the debug method from the React Native Testing Library<strong> </strong>check for any unexpected behaviors.</li><li>Continually updating the tests as you continue to develop the component to make sure all different states and behaviors are covered.</li></ol><p>The below example shows how a test suite looks like.</p><pre>import React from &#39;react&#39;;<br>import { render } from &#39;@testing-library/react-native&#39;;<br><br>describe(&#39;Render &lt;Component /&gt; correctly&#39;, () =&gt; {<br>  it(&#39;matches the snapshot&#39;, () =&gt; {<br>    // includes test function to match a snapshot<br>  });<br><br>  it(&#39;renders error screen when the data is invalid&#39;, () =&gt; {<br>    // expect assertion for error state<br>  });<br><br>  it(&#39;shows loading indicator when the data is being fetch&#39;, () =&gt; {<br>    // expect assertion for loading state<br>  });<br>})</pre><h4><a href="https://callstack.github.io/react-native-testing-library/docs/getting-started">React Native Testing Library</a> 🧚‍♂️</h4><p>React Native Testing Library (RNTL) is a testing library specifically designed for testing React Native components. It provides a set of utilities for rendering a component, querying a single element as well as simulating user interaction. Let’s go through a few essential APIs by React Native Testing Library.</p><p><strong>render()</strong> creates a virtual representation of a component and returns various of queries methods to test the behavior of a component.</p><pre>describe(&#39;Render &lt;Component /&gt; correctly&#39;, () =&gt; {<br>  it(&#39;shows loading indicator when the data is being fetch&#39;, () =&gt; {<br>    const { getByTestId, debug } = render(&lt;Component/&gt;);<br>    debug();<br>  });<br>})</pre><p><strong>debug()</strong> destructs the variable from the render method that is used to print the HTML structure of a component to the console. This is useful for debugging any failures or unexpected behavior of a component.</p><p><strong>waitFor()</strong> waits for the certain conditions to be true before continuing the next statement, this is useful when testing for asynchronous behavior of a component, i.e waiting for an element to be appear or disappear from the DOM. The duration of the timeout can be adjusted, default timeout is 5000ms.</p><p>Furthermore, you can use <strong>fireEvent</strong> to simulate user interactions by triggering the change and input events.</p><p>There are a total of six query methods for querying the matching element,</p><ul><li><strong>getBy</strong>: Returns the first element that matches the query, throws error if no elements match.</li><li><strong>getAllBy</strong>: Returns an array of all elements that match the query, throws error if no elements match.</li><li><strong>queryBy</strong>: Returns the first element that matches the query, returns <em>null</em> if no element match.</li><li><strong>queryAllBy</strong>: Returns an array of all elements that match the query, returns empty array if no elements match.</li><li><strong>findBy</strong>: Returns a promise that resolves to the first element that matches the query, throws error if no elements match.</li><li><strong>findAllBy</strong>: Returns a promise that resolves to an array of elements that match the query, throws error if no elements match.</li></ul><p>The table below shows the summary of the query methods,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/890/1*C-PljlSYuMuvXg0hFU87Vg.png" /></figure><p>Followed by commonly used query options, as in</p><ul><li><strong>ByText</strong>: Returns an element with matching text content.</li><li><strong>ByTestId</strong>: Returns an element with matching test ID of a component.</li><li><strong>ByPlaceholderText</strong>: Returns TextInput element with matching placeholder text.</li><li><strong>ByDisplayValue</strong>: Returns TextInput element with matching display value.</li></ul><p>The below table shows the query methods with options that are used to search for elements in the component tree based on the text content, test ID, placeholder or display value.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zINeMq1zGHkkDVIRHcxchw.png" /></figure><p>Here is an example of component and test suite to demonstrate the usage of React Native Testing Library’s API.</p><pre>// Component.js<br>import React from &#39;react&#39;;<br>import { FlatList, TouchableOpacity } from &#39;react-native&#39;;<br>import Item from &#39;./Item&#39;;<br><br>const data = [<br>  { id: &#39;1&#39;, text: &#39;Text 1&#39; },<br>  { id: &#39;2&#39;, text: &#39;Text 2&#39; },<br>  { id: &#39;3&#39;, text: &#39;Text 3&#39; },<br>];<br><br>const Component = ({ onItemPress }) =&gt; {<br>  const renderItem = ({ item }) =&gt; (<br>    &lt;TouchableOpacity onPress={() =&gt; onItemPress(item.id)}&gt;<br>      &lt;Item key={item.id} title={item.text} /&gt;<br>    &lt;/TouchableOpacity&gt;<br>  );<br><br>  return (<br>    &lt;FlatList<br>      testId=&quot;flat-list&quot;<br>      data={data}<br>      renderItem={renderItem}<br>      keyExtractor={(item) =&gt; item.id}<br>    /&gt;<br>  );<br>};<br><br>export default Component;<br><br><br>// __tests__/Component.test.js<br>import React from &#39;react&#39;;<br>import { render, fireEvent } from &#39;@testing-library/react-native&#39;;<br>import Component from &#39;../Component&#39;;<br><br>describe(&#39;render &lt;Component /&gt;&#39;, () =&gt; {<br>  it(&#39;renders items correctly&#39;, () =&gt; {<br>    const { getByTestId } = render(&lt;Component /&gt;);<br>    const list = getByTestId(&#39;flat-list&#39;);<br><br>    expect(list).toBeDefined();<br><br>    // expect the data length to be 3<br>    expect(list.props.data.length).toBe(3);<br>  });<br><br>  it(&#39;displays the correct item&#39;, () =&gt; {<br>    const { getByText } = render(&lt;Component /&gt;);<br>    const text1 = getByText(&#39;Text 1&#39;);<br>    const text2 = getByText(&#39;Text 2&#39;);<br>    const text3 = getByText(&#39;Text 3&#39;);<br><br>    expect(text1).toBeDefined();<br>    expect(text2).toBeDefined();<br>    expect(text3).toBeDefined();<br>  });<br><br>  it(&#39;onPressItem is called when pressed&#39;, () =&gt; {<br>    const onItemPressMock = jest.fn();<br>    const { getByText, getByTestId } = render(&lt;Component onItemPress={onItemPressMock}/&gt;);<br>    <br>    // find the flat-list and Text elements<br>    const list = getByTestId(&#39;flat-list&#39;);<br>    const text1 = getByText(&#39;Text 1&#39;);<br>      <br>    // simulate the press on &#39;Text 1&#39;.<br>    fireEvent.press(text1);<br><br>    // the onItemPressMock handle is called with the &#39;id&#39; of the item passed as an argument<br>    expect(onItemPressMock).toHaveBeenCalledWith(&#39;1&#39;);<br>  });<br>});</pre><h4><a href="https://testing-library.com/docs/ecosystem-jest-native/">Jest Native</a> 🧚‍♂️</h4><p>Jest Native is a library that provides additional matchers that make it easier to test React Native components.</p><p>Refer to this <a href="https://github.com/testing-library/jest-native">site</a> for summary usage for each of the utility function.</p><p>Rewrite the above test suite with jest-native by using <strong>toBeOnTheScreen</strong> and <strong>toHaveTextContent</strong> matchers, as below.</p><pre>// __tests__/Component.test.js<br>import React from &#39;react&#39;;<br>import { render, fireEvent } from &#39;@testing-library/react-native&#39;;<br>import Component from &#39;../Component&#39;;<br><br>describe(&#39;render &lt;Component /&gt;&#39;, () =&gt; {<br>  it(&#39;renders the item correctly&#39;, () =&gt; {<br>    const { getByTestId } = render(&lt;Component /&gt;);<br>    const list = getByTestId(&#39;flat-list&#39;);<br><br>    expect(list).toBeOnTheScreen();<br><br>    // expect the data length to be 3<br>    expect(list.props.data.length).toBe(3);<br>  });<br><br>  it(&#39;displays the correct item&#39;, () =&gt; {<br>    const { getByText } = render(&lt;Component /&gt;);<br>    const text1 = getByTestId(&#39;text-1&#39;);<br>    const text2 = getByTestId(&#39;text-2&#39;);<br>    const text3 = getByTestId(&#39;text-3&#39;);<br><br>    expect(text1).toHaveTextContent(&#39;Text 1&#39;);<br>    expect(text2).toHaveTextContent(&#39;Text 2&#39;);<br>    expect(text3).toHaveTextContent(&#39;Text 3&#39;);<br>  });<br>});</pre><p>While it is possible to use jest without jest-native, using jest-native makes testing React Native apps more efficient and easier to maintain, especially when testing specific React Native components.</p><h4><a href="https://jestjs.io/">Jest </a>🧚‍♂️</h4><p>This is a common JavaScript testing framework that provides a test runner, assertion library and mocking library. It covers a variety of use cases, from basic equality testing to more complex behaviors.</p><p>Mocking is particularly important for a complex application that rely on external services, APIs and components. We can isolate the component being tested and ensure that it is functioning correctly.</p><blockquote><a href="https://jestjs.io/docs/mock-function-api/">Mocking component</a></blockquote><p>There are several ways to mock an external components:</p><ol><li>Create a <strong>__mocks__</strong> directory under the same directory as the <strong>ChildComponent.js</strong> file and create a file named <strong>ChildComponent.js</strong> in the <strong>__mocks__</strong> directory, as below.</li></ol><pre>// __mocks__/ChildComponent.js<br>import React from &#39;react&#39;;<br>import { View } from &#39;react-native&#39;;<br><br>const MockedChildComponent = ({ children }) =&gt; {<br>  return &lt;View testID=&quot;mocked-child-component&quot;&gt;{children}&lt;/View&gt;;<br>};<br><br>export default MockedChildComponent;<br><br><br>// __tests__/Component.test.js<br>import React from &#39;react&#39;;<br>import { render } from &#39;@testing-library/react-native&#39;;<br>import Component from &#39;./Component&#39;;<br>import MockedChildComponent from &#39;./__mocks__/ChildComponent&#39;;<br><br>// mock the child component<br>jest.mock(&#39;./ChildComponent&#39;, () =&gt; MockedChildComponent);<br><br>describe(&#39;Component&#39;, () =&gt; {<br>  it(&#39;renders the mocked child component correctly&#39;, () =&gt; {<br>    const { getByTestId } = render(&lt;Component /&gt;);<br><br>    expect(getByTestId(&#39;mocked-child-component&#39;)).toBeOnTheScreen();<br>  });<br>});</pre><p>2. Mock the external component directly on the test file.</p><pre>// __tests__/Component.test.js<br>import React from &#39;react&#39;;<br>import { render } from &#39;@testing-library/react-native&#39;;<br>import Component from &#39;./Component&#39;;<br><br>// mock the child component<br>jest.mock(&#39;../ChildComponent&#39;, () =&gt; {<br>  return {<br>    __esModule: true,<br>    default: ({ children }) =&gt; {<br>      return &lt;mocked-child-component&gt;{children}&lt;/mocked-child-component &gt;;<br>    },<br>  };<br>});<br><br>describe(&#39;Component&#39;, () =&gt; {<br>  it(&#39;renders the mocked child component correctly&#39;, () =&gt; {<br>    const { getByTestId } = render(&lt;Component /&gt;);<br><br>    expect(getByTestId(&#39;mocked-child-component&#39;)).toHaveTextContent(&#39;Test&#39;);<br>  });<br>});</pre><p>Both methods are valid and they work in different scenarios. The first method is useful when the external component is used in multiple components, so just mock it and use it in multiple tests. The second method is useful when we need to mock the child component for a single test.</p><blockquote><a href="https://jestjs.io/docs/mock-function-api/">Mocking API</a></blockquote><pre>// api.js<br>export const getData = async () =&gt; {<br>  const response = await fetch(&#39;https://example.com&#39;, {<br>    method: &#39;GET<br>  });<br>  return response;<br>};<br><br>// Component.test.js<br><br>import { getData } from &#39;./api&#39;;<br>import Component from &#39;./Component&#39;;<br><br>const data = { id: 1, text: &#39;Text 1&#39; };<br>jest.mock(&#39;./api&#39;, () =&gt; ({<br>  getData: jest.fn().mockReturnValue(data),<br>}));<br><br>describe(&#39;Component&#39;, () =&gt; {<br>  it(&#39;displays the correct data&#39;, async () =&gt; {<br>    const { getByText } = render(&lt;Component /&gt;);<br>    const text1 = getByTestId(&#39;text-1&#39;);<br><br>    expect(text1).toHaveTextContent(&#39;Text 1&#39;);<br>  });<br>});</pre><p>The code above shows when the API is called when the component is active, it will use the mocked API instead of the real implementation, allowing us to test the component that displays the correct data without making any network requests. In this case, <strong>mockReturnValue </strong>is used for defining the value the mocked function returns.</p><blockquote><a href="https://jestjs.io/docs/mock-function-api/">Mocking function</a></blockquote><p>In order to mock a function, using jest.fn() can create a mock function to replace the real function in our code during testing.</p><p>We don’t need to mock every function, only functions that have external dependencies or side effects need to be mocked to ensure that the tests focus only on its behavior but not the behavior of its dependencies.</p><p>Testing a function without mocking,</p><pre>// utils.js<br>export const add = (a, b) =&gt; {<br>  return a + b;<br>}<br><br>// utils.test.js<br>import { add } from &#39;./utils&#39;;<br><br>describe(&#39;add function&#39;, () =&gt; {<br>  it(&#39;should add two numbers correctly&#39;, () =&gt; {<br>    expect(add(1, 1)).toEqual(2);<br>  });<br>});</pre><p>Testing a function with mocking,</p><pre>// Component.js<br>import React from &#39;react&#39;;<br>import { TouchableOpacity, Text } from &#39;react-native&#39;;<br><br>const Component = () =&gt; {<br>  const handlePress = () =&gt; {<br>    console.log(&#39;Button pressed!&#39;);<br>  };<br><br>  return (<br>    &lt;TouchableOpacity onPress={handlePress}&gt;<br>      &lt;Text&gt;Button&lt;/Text&gt;<br>    &lt;/TouchableOpacity&gt;<br>  );<br>};<br><br>export default Component;<br><br>// Component.test.js<br><br>import React from &#39;react&#39;;<br>import { render, fireEvent } from &#39;@testing-library/react-native&#39;;<br>import Component from &#39;./Component&#39;;<br><br>describe(&#39;Component&#39;, () =&gt; {<br>  it(&#39;calls handlePress when button is pressed&#39;, () =&gt; {<br>    const handlePress = jest.fn();<br>    const { getByText } = render(&lt;Component handlePress={handlePress} /&gt;);<br>    const button = getByText(&#39;Button&#39;);<br>    fireEvent.press(button);<br>    expect(handlePress).toHaveBeenCalled();<br>  });<br>});</pre><p>In this case, the mock function is created for the <strong>handlePress </strong>to test the functionality of the <strong>handlePress</strong> independently to the component. Therefore, we are able to ensure that it is worked as expected.</p><p>jest.fn() replaces a function and we can assert that the function was called with specific arguments, was it being called, or how many times it was called. This way, you can test the behavior of a component without depending on external resources.</p><h4><a href="https://jestjs.io/docs/snapshot-testing">Snapshot testing </a>🧚‍♂️</h4><p>This is another technique for testing a component by capturing a snapshot of a component and compare it to previous snapshots to detect for any unexpected changes.</p><pre>// Component.js<br>import React from &#39;react&#39;;<br>import { render } from &#39;@testing-library/react-native&#39;;<br>import Component from &#39;../MyComponent&#39;;<br><br>describe(&#39;Component&#39;, () =&gt; {<br>  it(&#39;renders component correctly&#39;, () =&gt; {<br>    const { toJSON } = render(&lt;MyComponent /&gt;);<br>    expect(toJSON()).toMatchSnapshot();<br>  });<br>});<br><br>// Component.test.js.snap<br><br>exports[`renders component correctly`] = `<br>&lt;View<br>  style={<br>    Object {<br>      &quot;backgroundColor&quot;: &quot;black&quot;,<br>    }<br>  }<br>&gt;<br>  &lt;Text<br>    style={<br>      Object {<br>        &quot;color&quot;: &quot;white&quot;,<br>        &quot;fontSize&quot;: 12,<br>      }<br>    }<br>  &gt;<br>    Text 1<br>  &lt;/Text&gt;<br>&lt;/View&gt;<br>`;</pre><p>In this example, toMatchSnapshot() method is used to compare the rendered output to a saved snapshot of the component. It will create a snapshot of the rendered output in a file if we run it for the first time.</p><p>If the rendered output matches the snapshot, then the test passes. otherwise jest will display the changes and prompt to update the snapshot if necessary.</p><p>By using the React Native Testing Library in conjunction with Jest Native and Jest can provide a comprehensive testing for React Native components.</p><p>The combination of these tools make testing component rendering and behaviors much better. In overall, it could improve code coverage, boost our confidence in any code changes by catching bugs or failures before making it to production.</p><p>For your information, React Native Testing Library does not support end-to-end testing, but it is still possible to use it in combination with other tools <em>(e.g Cypress or Detox)</em> to perform end-to-end testing.</p><p>There are some thoughts when it comes to whether we should write tests or build a component first.</p><p>Test-driven development (TDD) is one of the development method which involves writing tests before writing the code to ensure the overall code is well-designed and testable. The other way is to write code first before adding the tests, but it may lead to poor code coverage.</p><p>Nonetheless, there are always pros and cons on every approach. Utilising the TDD method can leads to a better quality of code, while the latter is useful for a small to mid sized project as the code coverage can be easily improved. The best approach is always depends on the size of the project and try to aim for a balance between writing code and tests. 😉</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=608feadc82df" width="1" height="1" alt=""><hr><p><a href="https://medium.com/aia-sg-techblog/guide-to-react-native-testing-library-608feadc82df">Guide to React Native Testing Library</a> was originally published in <a href="https://medium.com/aia-sg-techblog">AIA Singapore Technology Blog</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Performance optimization in React Native]]></title>
            <link>https://medium.com/aia-sg-techblog/performance-optimization-in-react-native-8cb48070aa77?source=rss-4e6df3e6ef0c------2</link>
            <guid isPermaLink="false">https://medium.com/p/8cb48070aa77</guid>
            <category><![CDATA[react-native]]></category>
            <category><![CDATA[performance-optimization]]></category>
            <dc:creator><![CDATA[kahmun]]></dc:creator>
            <pubDate>Mon, 13 Mar 2023 09:14:25 GMT</pubDate>
            <atom:updated>2023-03-13T09:21:41.067Z</atom:updated>
            <content:encoded><![CDATA[<p>Waiting for an app to load is like waiting for a pot of water to boil. ⏳</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*-g17mh4j2KzQy3Qn" /></figure><p>When you are scrolling through an app, or visit a website, sometimes you may notice certain content seem to load more slowly than others. It’s natural to wonder if the issue is related to your phone or network. Then you start frustrating about it.</p><p>In today’s fast paced world, building responsive and high performant app is more important than before. Users expect seamless experiences with blazing-fast load time. However, as an application grows in complexity, we may be experience performance issues that can impact user experiences. Not only that, it also impacts usability and results in a loss of interest from audience.</p><p>Consequently, performance tuning has become an essential part of developer’s life, regardless of the specific technology or the framework being used.</p><p>One day, I was tasked with improving the performance of customer listing that needed to load from 500 up to 6000 datasets. Unfortunately, the initial load time was already quite slow, taking close to 15 seconds or more to load 500 datasets. 😤 This meant that any additional load time from a larger listing would be unacceptable to users, and even myself. Therefore, it is crucial to optimize the performance as much as possible to keep the load time at minimum.</p><p>In case of React Native, performance tuning can take many forms, from optimizing the app’s rendering to reducing the number of unnecessary re-renders. Let’s roll up our sleeves and get started to dive into our journey of performance optimizing.</p><h4><strong>Remove console.log statements 🧚‍♂️</strong></h4><p>Are you the one who always forgets to remove console.log statements? It has a negative impact on performance as well as slower code execution. To avoid this, it’s important to remove all console.log statements before deploying the app to production.</p><h4>Best practices and efficient code 🧚‍♂️</h4><p>Many of us might not be aware that certain coding practices can have a small impact on performance, especially if the component is re-rendered frequently. For example,</p><pre>&lt;Button<br>  onPress={() =&gt; {<br>    setError(true);<br>    setLoading(false);<br>  }}<br>&gt;<br>&lt;/Button&gt;</pre><p>The arrow function creates every time the component is rendered, which can cause unnecessary re-renders, we can define the function outside and pass it as a reference, hence, the <em>handlePress</em> is only created once.</p><pre>const handlePress = () =&gt; {<br>  setError(true);<br>  setLoading(false);<br>};<br><br>// Inside your component<br>&lt;Button onPress={handlePress} /&gt;</pre><p>Most of the time, following best practices can certainly improve performance, it keeps the code cleaner, more readable, maintainable in the future.</p><h4><strong>Make use of Functional Component 🧚‍♂️</strong></h4><p>It can be more difficult to tune performance with class-based component than with functional component due to the complex structure and reliance on lifecycle methods.</p><p>While functional component is simpler and more concise, there are still some situations where class-based component might be appropriate like validating complex state.</p><p>In this case, when it comes to fetching and rendering a huge list of data, functional component might be a better choice for performance reasons. The React hooks is optimized for performance and help prevent unnecessary re-renders or other computations.</p><p>Rewriting the component with functional component can be relatively straightforward process, as below:</p><blockquote>Class-based component</blockquote><pre>import React, { Component } from &#39;react&#39;;<br>import { View, Text } from &#39;react-native&#39;;<br><br>class MyComponent extends Component {<br>  constructor(props) {<br>    super(props);<br>    this.state = {<br>      count: 0<br>    };<br>  }<br><br>  render() {<br>    return (<br>      &lt;View&gt;<br>        &lt;Text&gt;Hello World!&lt;/Text&gt;<br>      &lt;/View&gt;<br>    );<br>  }<br>}<br><br>export default MyComponent;</pre><blockquote>Functional component</blockquote><pre>import React, { useState } from &#39;react&#39;;<br>import { View, Text } from &#39;react-native&#39;;<br><br>const MyComponent = () =&gt; {<br>  const [count, setCount] = useState(0);<br><br>  return (<br>    &lt;View&gt;<br>      &lt;Text&gt;Hello World!&lt;/Text&gt;<br>    &lt;/View&gt;<br>  );<br>};<br><br>export default MyComponent;</pre><p>However, the decision to use class-based or functional component depends on the needs of an application or specific requirements. It is advisable to measure and compare the performance of both approaches before making the final decision.</p><h4>React Query 🧚‍♂️</h4><p><a href="https://react-query-v3.tanstack.com/">React query</a> is known for one of the popular data fetching library that is optimized for server state caching, real-time data synchronization and background updates.</p><blockquote>Before using React Query</blockquote><pre>const [list, setList] = useState([]);<br>const [isLoading, setIsLoading] = useState(false);<br>const [isError, setIsError] = useState(false);<br><br>useEffect(() =&gt; {<br>  const fetchList = async () =&gt; {<br>    setIsError(false);<br>    setIsLoading(true);<br><br>    try {<br>      const result = await fetch(&#39;https://example.com/list&#39;);<br>      const json = await result.json();<br>      setData(json);<br>    } catch (error) {<br>      setIsError(true);<br>    }<br><br>    setIsLoading(false);<br>  };<br><br>  fetchList();<br>}, []);</pre><p>One thing I like the most about React Query is that we don’t need to manage the loading state and error state ourselves using <strong><em>useState. </em></strong>Instead, we can use <strong><em>useQuery</em></strong> hook to fetch the data and handle the loading and error states automatically.</p><blockquote>After using React-Query</blockquote><pre>import { useQuery } from &#39;react-query&#39;;<br><br>function MyComponent() {<br>  const { isLoading, error, data } = useQuery(&#39;list&#39;, () =&gt;<br>    fetch(&#39;https://sample.com/list&#39;).then(res =&gt; res.json());<br><br>  if (isLoading) return &lt;View&gt;&#39;Loading...&#39;&lt;/View&gt;;<br>  if (error) return &lt;View&gt;`An error has occurred: ${error.message}`&lt;/View&gt;;<br><br>  return (<br>    &lt;View&gt;<br>      &lt;Text&gt;{data}&lt;/Text&gt;<br>    &lt;/View&gt;<br>  );<br>}</pre><p>The data fetching is done just in one line and thus it reduces amount of code and significantly improves the performance without having unnecessary re-renders caused by updating the state.</p><p>Some of you might wonder if Redux can be replaced by React Query? The answer is NO ❌. Both Redux and React Query are optimized for different use cases. Redux, on the other hand, provides a predictable global state management that can be used throughout an application.</p><p>In fact, both libraries can be used together to create a more robust application — a more efficient data fetching with React Query and a complete UI state management with Redux.</p><h4>Remove unnecessary API calls 🧚‍♂️</h4><p>Checking for unnecessary API calls is an essential part of performance optimization as well. In many cases, API calls can be expensive so make sure that they are only made when necessary.</p><p>It also can be achieved through caching and conditional rendering. This means that when the data is fetched, it is stored in a cache. When the data is requested again, it can be retrieved from the cache rather than making another API call.</p><p>Then again, if the data is only required for a specific component, it can only be requested and rendered when the component is active.</p><h4>Partial data fetching 🧚‍♂️</h4><p>Another feasible approach is to fetch a portion of data, e.g. the first 100 out of 500 datasets, followed by requesting and rendering the rest of the data.</p><p>Some modifications needed to be made on the API endpoint by specifying the number of data to be retrieved. The API endpoint can be modified to accept a query parameter <strong><em>limit</em> </strong>that specifies the maximum number of data to be retrieved in a single request.</p><p>In client side code, the application makes an initial request to retrieve the first 100 data and render them on the screen. Then, make the request again from the background to fetch the entire data.</p><p>Partial data fetching also can be achieved through a several methods, including pagination, infinite scrolling, and lazy loading. Pagination allows dividing the data into smaller chunks and displaying them on separate pages, while infinite scrolling loads more data as the user scrolls down the page and lazy loading involves loading data as it becomes necessary, such as when the user clicks on a particular section.</p><p>As a result, it improves the performance and usability of the application, as well as reduce the server load and optimize bandwidth usage.</p><p>Voila! ✨ By implementing these approaches for performance optimization, we were able to drastically reduce customer listing’s load time from an average of 15 seconds to just only 2 seconds with the help from our back-end optmization as well. Our users become happy again. 🤪</p><p>But keep in mind, the application performance deteriorates when it grows in complexity, new features are added and more data is processed. Therefore, performance optimization is an ongoing process and be sure to continually adjust your app as needed. 💪🏻</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8cb48070aa77" width="1" height="1" alt=""><hr><p><a href="https://medium.com/aia-sg-techblog/performance-optimization-in-react-native-8cb48070aa77">Performance optimization in React Native</a> was originally published in <a href="https://medium.com/aia-sg-techblog">AIA Singapore Technology Blog</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>