<?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 WangYeUX on Medium]]></title>
        <description><![CDATA[Stories by WangYeUX on Medium]]></description>
        <link>https://medium.com/@wangyeux?source=rss-65a29ce9d43a------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*9CGzYdozRdFOgras</url>
            <title>Stories by WangYeUX on Medium</title>
            <link>https://medium.com/@wangyeux?source=rss-65a29ce9d43a------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 14:37:43 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@wangyeux/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[LLM Caching Best Practices: From Exact Keys to Semantic Conversation Matching]]></title>
            <link>https://wangyeux.medium.com/llm-caching-best-practices-from-exact-keys-to-semantic-conversation-matching-8b06b177a947?source=rss-65a29ce9d43a------2</link>
            <guid isPermaLink="false">https://medium.com/p/8b06b177a947</guid>
            <category><![CDATA[cache]]></category>
            <category><![CDATA[llm]]></category>
            <dc:creator><![CDATA[WangYeUX]]></dc:creator>
            <pubDate>Fri, 15 Aug 2025 09:15:21 GMT</pubDate>
            <atom:updated>2025-08-15T09:15:21.229Z</atom:updated>
            <content:encoded><![CDATA[<p>Caching is the single highest-leverage optimization for LLM applications. Done well, it cuts cost and latency dramatically while improving consistency for repeated prompts, tool calls, and workflows.</p><p>## TL;DR</p><p>- **What to cache**: LLM responses and tool call results.</p><p>- **How to cache**: Start with **exact match**; add **semantic match** for near-duplicates.</p><p>- **Semantic strategy**: Cache and search over the entire conversation history (not just the last prompt). If the history is too long, **summarize first**, then embed and search. After semantic hit, **exactly filter** on model and parameters (temperature, system prompt, tools, etc.).</p><p>## Why cache LLMs?</p><p>- **Latency**: Return results in milliseconds instead of seconds.</p><p>- **Cost**: Reduce token spend and downstream tool usage.</p><p>- **Stability**: Make responses deterministic for repeat prompts.</p><p>- **Scalability**: Smooth traffic spikes and protect providers/tools.</p><p>— -</p><p>## What to cache</p><p>- **LLM responses**: Final model outputs (text, JSON, images) along with the inputs and generation settings used to produce them.</p><p>- **Tool call results**: Deterministic or slow/expensive calls invoked by the LLM (e.g., database queries, web searches, vector lookups, retrieval pipelines). These often dominate latency and cost.</p><p>Pro tip: Cache tool results separately from LLM responses. Even when a conversation changes slightly, a deterministic tool result can still be reused.</p><p>— -</p><p>## How to cache</p><p>### 1) Exact match</p><p>Key an entry using a normalized fingerprint of all inputs that materially affect the output:</p><p>- **Model identity**: provider, model version.</p><p>- **Generation params**: temperature, top_p, max_tokens, stop sequences, seed.</p><p>- **System and developer prompts**.</p><p>- **User-visible inputs**: last prompt and, if relevant, full/rolled conversation context.</p><p>- **Tools/functions schema**: names, arguments schema, and versions.</p><p>- **Post-processing switches**: e.g., JSON-mode, function-calling on/off.</p><p>Example key construction in Python:</p><p>```python</p><p><em>import</em> hashlib</p><p><em>import</em> json</p><p>def normalized_json(<em>data</em>: dict) -&gt; str:</p><p><em>return</em> json.dumps(data, <em>ensure_ascii</em>=False, <em>sort_keys</em>=True, <em>separators</em>=(“,”, “:”))</p><p>def build_cache_key(</p><p>*,</p><p><em>model</em>: str,</p><p><em>params</em>: dict,</p><p><em>system_prompt</em>: str,</p><p><em>messages</em>: list,</p><p><em>tools_schema</em>: list | None = None,</p><p><em>postprocessing_flags</em>: dict | None = None,</p><p>) -&gt; str:</p><p>payload = {</p><p>“model”: model,</p><p>“params”: params,</p><p>“system”: system_prompt.strip(),</p><p>“messages”: messages, <em># already normalized (roles/content)</em></p><p>“tools”: tools_schema or [],</p><p>“post”: postprocessing_flags or {},</p><p>}</p><p>fingerprint = normalized_json(payload)</p><p><em>return</em> hashlib.sha256(fingerprint.encode(“utf-8”)).hexdigest()</p><p>```</p><p>Use this key to store and retrieve exact matches in a fast key-value store (e.g., Redis, SQLite, DynamoDB, Postgres).</p><p>### 2) Semantic match</p><p>For near-duplicate prompts or paraphrases, embed the conversation context and use a vector database to find semantically similar cache entries.</p><p>Core ingredients:</p><p>- **What to embed**: the entire conversation history (system + user/assistant messages + tool call summaries) rather than only the latest user message.</p><p>- **When too long**: summarize first, then embed.</p><p>- **After a semantic hit**: run an exact filter (model, temperature, system prompt, tools) to ensure high-precision reuse.</p><p>— -</p><p>## Strategy for semantic caching</p><p>### Store and search over the full context</p><p>Do not only embed the last prompt. The same last prompt in a different conversation can require a different answer. Embed a representation of the entire conversation history.</p><p>When the context is over token or length limits, first summarize to a stable, instruction-preserving synopsis. Then embed that synopsis.</p><p>### Step 1: Semantic search (on the entire history)</p><p>1. Concatenate the normalized conversation into a single string: system prompt + messages + lightweight tool outputs.</p><p>2. If over your token/length threshold, generate a summary that preserves constraints, facts, and references.</p><p>3. Create a vector embedding from this (full history or summary).</p><p>4. Query your vector DB for the top-k most similar cached histories.</p><p>### Step 2: Exact filtering</p><p>For each candidate returned by semantic search, only accept it if the following match exactly:</p><p>- Model (and version)</p><p>- Temperature and generation parameters (top_p, max_tokens, stop, seed)</p><p>- System/developer prompts</p><p>- Tools/function schemas and their versions</p><p>- Critical post-processing flags (e.g., JSON-mode)</p><p>If multiple candidates pass, prefer the one with the smallest semantic distance or the most recent.</p><p>— -</p><p>## Example: conversation-aware semantic cache (Python-ish pseudocode)</p><p>```python</p><p><em>from</em> typing <em>import</em> Any, Optional</p><p>TOKEN_LIMIT_FOR_EMBED = 4000</p><p>def concat_history(<em>system</em>: str, <em>messages</em>: list[dict[str, Any]], <em>tool_summaries</em>: list[str]) -&gt; str:</p><p>parts = [f”&lt;system&gt;\n{system.strip()}\n&lt;/system&gt;”]</p><p><em>for</em> m <em>in</em> messages:</p><p>parts.append(f”&lt;{m[‘role’]}&gt;\n{m[‘content’].strip()}\n&lt;/{m[‘role’]}&gt;”)</p><p><em>for</em> t <em>in</em> tool_summaries:</p><p>parts.append(f”&lt;tool&gt;\n{t.strip()}\n&lt;/tool&gt;”)</p><p><em>return</em> “\n\n”.join(parts)</p><p>def summarize_if_needed(<em>text</em>: str, <em>token_limit</em>: int, <em>summarize_fn</em>) -&gt; str:</p><p><em>if</em> estimate_tokens(text) &lt;= token_limit:</p><p><em>return</em> text</p><p><em># The summary must preserve instructions, constraints, referenced entities, and key facts</em></p><p><em>return</em> summarize_fn(text)</p><p>def embed_context(<em>text</em>: str, <em>embed_fn</em>) -&gt; list[float]:</p><p><em>return</em> embed_fn(text)</p><p>def semantic_candidates(<em>vector</em>: list[float], <em>top_k</em>: int, <em>vector_db</em>) -&gt; list[dict]:</p><p><em>return</em> vector_db.search(vector, <em>top_k</em>=top_k)</p><p>def exact_filter(<em>cands</em>: list[dict], <em>key_fields</em>: dict) -&gt; Optional[dict]:</p><p><em>for</em> c <em>in</em> cands:</p><p><em>if</em> all(c[ft] == key_fields[ft] <em>for</em> ft <em>in</em> key_fields):</p><p><em>return</em> c</p><p><em>return</em> None</p><p>def get_or_generate(</p><p>*, <em>model</em>, <em>params</em>, <em>system</em>, <em>messages</em>, <em>tools_schema</em>, <em>post_flags</em>,</p><p><em>embed_fn</em>, <em>summarize_fn</em>, <em>vector_db</em>, <em>kv_cache</em></p><p>):</p><p><em># 1) Exact match first</em></p><p>exact_key = build_cache_key(</p><p><em>model</em>=model, <em>params</em>=params, <em>system_prompt</em>=system,</p><p><em>messages</em>=messages, <em>tools_schema</em>=tools_schema, <em>postprocessing_flags</em>=post_flags</p><p>)</p><p><em>if</em> (hit := kv_cache.get(exact_key)) is not None:</p><p><em>return</em> hit</p><p><em># 2) Semantic search on conversation history (summarize if needed)</em></p><p>history = concat_history(system, messages, <em>tool_summaries</em>=extract_tool_summaries(messages))</p><p>to_embed = summarize_if_needed(history, TOKEN_LIMIT_FOR_EMBED, summarize_fn)</p><p>vector = embed_context(to_embed, embed_fn)</p><p>cands = semantic_candidates(vector, <em>top_k</em>=10, <em>vector_db</em>=vector_db)</p><p><em># 3) Exact filtering on critical fields</em></p><p>key_fields = {</p><p>“model”: model,</p><p>“params”: normalized_json(params),</p><p>}</p><p><em>if</em> (cand := exact_filter(cands, key_fields)) is not None:</p><p>kv_cache.touch(cand[“exact_key”]) <em># optional: refresh TTL</em></p><p><em>return</em> cand[“response”]</p><p><em># 4) Miss: call the model, then write-through</em></p><p>response = call_llm(model, params, messages,)</p><p>kv_cache.set(exact_key, response)</p><p>vector_db.upsert({</p><p>“vector”: vector,</p><p>“exact_key”: exact_key,</p><p>**key_fields,</p><p>“response”: response,</p><p>})</p><p><em>return</em> response</p><p>```</p><p>— -</p><p>## Caching tool calls</p><p>Treat tools as first-class cacheable components.</p><p>- **Key**: function name + normalized parameters.</p><p>- **TTL**: set freshness windows based on data volatility. For dynamic sources, use short TTL or revalidation.</p><p>- **Staleness and revalidation**: adopt a stale-while-revalidate strategy for fast returns with background refresh.</p><p>- **Error handling**: cache negative results sparingly (e.g., 404s) with very short TTLs.</p><p>Example tool cache key:</p><p>```python</p><p><em>import</em> hashlib</p><p>def build_tool_key(<em>name</em>: str, <em>params</em>: dict) -&gt; str:</p><p>payload = {“tool”: name, “params”: params}</p><p><em>return</em> hashlib.sha256(normalized_json(payload).encode(“utf-8”)).hexdigest()</p><p>```</p><p>— -</p><p>## Quality guardrails for semantic caching</p><p>- **Thresholds**: require a minimum cosine similarity for acceptance; tune per domain.</p><p>- **Re-ranking**: optionally re-score top-k candidates with a cross-encoder or small reranker.</p><p>- **Determinism**: set seed where supported to make cache hits repeatable.</p><p>- **Versioning**: version your embedder and prompt templates. A change should invalidate or re-embed.</p><p>— -</p><p>## Invalidation and lifecycle</p><p>- **Automatic invalidation**: include versions of prompts, tools, and embeddings in keys.</p><p>- **TTL/refresh**: choose TTLs based on business needs. Consider touch-on-hit to keep hot entries alive.</p><p>- **Eviction**: use size-based eviction (LRU/LFU) and cost-aware policies (evict cheap-to-recompute first).</p><p>- **Observability**: log hit/miss, store read/write latency, and approximate savings (tokens, $).</p><p>— -</p><p>## Checklist</p><p>- **Cache LLM responses and tool results** separately.</p><p>- **Exact match first**, then **semantic match**.</p><p>- **Embed full conversation history**; if too long, **summarize then embed**.</p><p>- After semantic hit, **exactly filter** on model, params, system, tools, and flags.</p><p>- **Version** prompts, tools, and embeddings to control invalidation.</p><p>- **Add TTLs**, staleness policies, and **observability**.</p><p>— -</p><p>## Final note</p><p>Start simple: deploy exact-match caching on day one. Layer in semantic caching once you have stable prompts and telemetry. The combination delivers the best of both worlds: precision when it matters and recall for paraphrases and near-duplicates.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8b06b177a947" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[CSS animation trick]]></title>
            <link>https://wangyeux.medium.com/css-animation-trick-37093b382714?source=rss-65a29ce9d43a------2</link>
            <guid isPermaLink="false">https://medium.com/p/37093b382714</guid>
            <category><![CDATA[css-animation]]></category>
            <dc:creator><![CDATA[WangYeUX]]></dc:creator>
            <pubDate>Fri, 01 Sep 2023 08:18:13 GMT</pubDate>
            <atom:updated>2023-09-01T08:18:13.213Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FrRFIuu2TIaTcQk-czyREg.jpeg" /></figure><p>When attempting to implement a collapsible component with CSS animation, I encountered an issue where the content underneath the collapse component appeared to overlap. This problem arose due to the default ‘overflow’ property being set to ‘visible.’ This setting means that during the collapse animation, the height of the content container decreases, but the content itself remains visible outside of the container.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FgxNAUIuhBZc%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DgxNAUIuhBZc&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FgxNAUIuhBZc%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="640" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/5cb4d2667eaa9b347b8c4f91a5cb3518/href">https://medium.com/media/5cb4d2667eaa9b347b8c4f91a5cb3518/href</a></iframe><p>To resolve this issue, you can simply apply the ‘overflow: hidden’ CSS property to the collapse content. This adjustment ensures that the content within the collapse container remains hidden as it contracts, preventing any unwanted overlap with other elements.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2F9UWhX3Ubur0&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3D9UWhX3Ubur0&amp;image=http%3A%2F%2Fi.ytimg.com%2Fvi%2F9UWhX3Ubur0%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/b499518ddac2c66f57a27e16b9ce2778/href">https://medium.com/media/b499518ddac2c66f57a27e16b9ce2778/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=37093b382714" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[BFC — Block Formatting Context in CSS]]></title>
            <link>https://wangyeux.medium.com/bfc-block-formatting-context-in-css-d3eb384317e2?source=rss-65a29ce9d43a------2</link>
            <guid isPermaLink="false">https://medium.com/p/d3eb384317e2</guid>
            <category><![CDATA[css]]></category>
            <category><![CDATA[block-formatting-context]]></category>
            <category><![CDATA[web-development]]></category>
            <dc:creator><![CDATA[WangYeUX]]></dc:creator>
            <pubDate>Thu, 08 Apr 2021 12:51:03 GMT</pubDate>
            <atom:updated>2021-04-08T12:53:15.753Z</atom:updated>
            <content:encoded><![CDATA[<h3>BFC — Block Formatting Context in CSS</h3><p>Much of the information in this article comes from <a href="https://developer.mozilla.org/en-US/docs/Web/Guide/CSS/Block_formatting_context">MDN</a>. You can go to the further reading section for more details.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YpVHkGivVdR-X6mqbiMZyg.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@louishansel?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Louis Hansel @shotsoflouis</a> on <a href="https://unsplash.com/s/photos/chessboard?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><h3>What is BFC</h3><p>A BFC(block formatting context) is a mini layout system on your page. Everything in the BFC will not interfere with the outer world.</p><p>It is worth mentioning that a Flex/Grid container element can create a Flex/Grid formatting context, which is very similar to a BFC except they cannot have floating child elements. However, using Flex and Grid can still solve external float and margin collapse problems.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcodesandbox.io%2Fembed%2Fvdmkk&amp;display_name=CodeSandbox&amp;url=https%3A%2F%2Fcodesandbox.io%2Fs%2Fvdmkk&amp;image=https%3A%2F%2Fcodesandbox.io%2Fapi%2Fv1%2Fsandboxes%2Fvdmkk%2Fscreenshot.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=codesandbox" width="1000" height="500" frameborder="0" scrolling="no"><a href="https://medium.com/media/4f998aafab37dde852fa53a650b36efa/href">https://medium.com/media/4f998aafab37dde852fa53a650b36efa/href</a></iframe><h3>How to create a BFC</h3><p>There are multiple ways to create a BFC. Here are just some common methods.</p><ul><li>The root element of the document.</li><li>Elements with display CSS property set to “flow-root”, which makes it similar to the root element of the document.</li><li>Elements with float CSS property that is not “none”.</li><li>Elements with position CSS property set to “absolute” or “fixed”.</li><li>Direct child elements of Flex/Grid container when themselves are not Flex, Grid, or Table container.</li><li>……</li></ul><h3>What problems can BFC solve</h3><h4>Contain inner float</h4><p>Internally floating elements will break away from the normal document flow. As a result, the floating elements will not be wrapped by their parent element.</p><p>Making the container to be a BFC can enable it to contain a float child element.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcodesandbox.io%2Fembed%2Fg44fn&amp;display_name=CodeSandbox&amp;url=https%3A%2F%2Fcodesandbox.io%2Fs%2Fg44fn&amp;image=https%3A%2F%2Fcodesandbox.io%2Fapi%2Fv1%2Fsandboxes%2Fg44fn%2Fscreenshot.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=codesandbox" width="1000" height="500" frameborder="0" scrolling="no"><a href="https://medium.com/media/6101a38fc25c2ff09356059fe14bba0a/href">https://medium.com/media/6101a38fc25c2ff09356059fe14bba0a/href</a></iframe><h4>Exclude external float</h4><p>As above, a floating element will break away from normal document flow and overlap with its sibling element. If will turn this sibling element into a BFC, they will not overlap again.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcodesandbox.io%2Fembed%2Fz2oeb&amp;display_name=CodeSandbox&amp;url=https%3A%2F%2Fcodesandbox.io%2Fs%2Fz2oeb&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=codesandbox" width="1000" height="500" frameborder="0" scrolling="no"><a href="https://medium.com/media/8ab3f4361f0a8f2c02677589336522c5/href">https://medium.com/media/8ab3f4361f0a8f2c02677589336522c5/href</a></iframe><h4>Prevent margin collapse</h4><p>Sometimes the top and bottom margin of two elements will collapse into a single margin. Making these two elements into different BFC can prevent margin collapse.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcodesandbox.io%2Fembed%2Fox6h7&amp;display_name=CodeSandbox&amp;url=https%3A%2F%2Fcodesandbox.io%2Fs%2Fox6h7&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=codesandbox" width="1000" height="500" frameborder="0" scrolling="no"><a href="https://medium.com/media/0ba2525feda6651109c0758631c4a805/href">https://medium.com/media/0ba2525feda6651109c0758631c4a805/href</a></iframe><h3>Further Reading</h3><ul><li><a href="https://developer.mozilla.org/en-US/docs/Web/Guide/CSS/Block_formatting_context">Block formatting context - Developer guides | MDN</a></li><li><a href="https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Flow_Layout/Intro_to_formatting_contexts">Introduction to formatting contexts</a></li><li><a href="https://medium.com/@ritz078/block-formatting-contexts-in-css-3a9555355019">Block Formatting Contexts in CSS</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d3eb384317e2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The React component lifecycle]]></title>
            <link>https://wangyeux.medium.com/the-react-component-lifecycle-b364a0027550?source=rss-65a29ce9d43a------2</link>
            <guid isPermaLink="false">https://medium.com/p/b364a0027550</guid>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[reactjs]]></category>
            <dc:creator><![CDATA[WangYeUX]]></dc:creator>
            <pubDate>Fri, 02 Apr 2021 11:41:52 GMT</pubDate>
            <atom:updated>2021-04-06T06:29:42.699Z</atom:updated>
            <content:encoded><![CDATA[<p>What is React component lifecycle? You can think of the lifecycle as the different stages of a component from birth to death.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gwjnROychYQnKFoqeNxP-w.png" /><figcaption><a href="https://projects.wojtekmaj.pl/react-lifecycle-methods-diagram/">https://projects.wojtekmaj.pl/react-lifecycle-methods-diagram/</a></figcaption></figure><h3>Three major phases of a component’s lifecycle</h3><h4>Mounting</h4><p><strong>constructor</strong></p><p>It is called before mounting the component into DOM.</p><p>It is the place where you initialize the local state and binds event methods.</p><p><strong>render()</strong></p><p>The render method is the only required method in a class component. It should be noted that it is different from the ReactDOM.render().</p><pre>render()</pre><p>Component.render() takes no arguments and returns the corresponding React element tree for the component. Component.render() is called when the component’s state or props change and shouldComponentUpdate() lifecycle method return true. It returns a new React element tree based on the changed state and props.</p><pre>ReactDOM.render(element, container[, callback])</pre><p>ReactDOM.render(), on the other side, takes a React element tree and a container DOM element as arguments. It turns the React element into corresponding DOM element and then mounting the DOM element into the container DOM element.</p><p><strong>componentDidMount()</strong></p><p>componentDidMount() will be invoked immediately after the component is mounted into a container DOM node.</p><p>Anythings that requires DOM nodes should be called there. For example, fetching data from a remote endpoint. Besides, you can call setState there, and the re-render will happen before the browser updates the screen cause some optimation of React. In other words, the user will only see one rendering even though setState() will trigger a re-render.</p><h4>Updating</h4><p><strong>render()</strong></p><p>In the updating phase, any state or props changes will trigger a re-render. Other than that, it is no different than render() in the mounting phase.</p><p><strong>componentDidUpdate()</strong></p><pre>componentDidUpdate(prevProps, prevState, snapshot)</pre><p>componentDidupdate() is invoked immediately after updating occurs. However, it will not be called when initializing the component.</p><p>You can invoke network requests in this phase.</p><p>Also, you can use setState() in this phase. However, be careful to wrap setState() in a condition in order to avoid an infinite loop. The inner theory is obvious, a state change can cause React updating process, which will trigger the componentDidUpdate() again.</p><h4>Unmounting</h4><p><strong>componentWillUnmount()</strong></p><p>componentWillUnmount() will be invoked immediately before a component is unmounted. You should implement any unsubscribe actions there.</p><pre>ReactDOM.unmountComponentAtNode(container)</pre><p>You can use ReactDOM.unmountComponentAtNode() to unmount a mounted component.</p><p><a href="https://reactjs.org/docs/react-component.html">React.Component - React</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b364a0027550" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[What are react hooks and how to use them]]></title>
            <link>https://wangyeux.medium.com/what-are-react-hooks-and-how-to-use-them-e202553eacc4?source=rss-65a29ce9d43a------2</link>
            <guid isPermaLink="false">https://medium.com/p/e202553eacc4</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[react-hook]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[web-development]]></category>
            <dc:creator><![CDATA[WangYeUX]]></dc:creator>
            <pubDate>Wed, 24 Mar 2021 11:09:42 GMT</pubDate>
            <atom:updated>2021-03-26T02:40:36.799Z</atom:updated>
            <content:encoded><![CDATA[<p>React hooks hook out great features of react for your to use in functional components.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YABcj8wX3zX93BNNK6lBzA.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@chuttersnap?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">CHUTTERSNAP</a> on <a href="https://medium.com/s/photos/hook?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><h3>What are React hooks</h3><p>Hooks are functions that hook into react state and lifecycle features from the function component. It does not work in class components.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lFUv4fPCgn8q3V_gfNENBA.png" /><figcaption><a href="https://reactjs.org/docs/hooks-reference.html">https://reactjs.org/docs/hooks-reference.html</a></figcaption></figure><h3>Why should we write hooks instead of class-based components</h3><p><a href="https://blog.bitsrc.io/6-reasons-to-use-react-hooks-instead-of-classes-7e3ee745fe04">6 Reasons to Use React Hooks Instead of Classes</a></p><h3>useState</h3><p>The ‘useState” hook returns a state value equal to the initial state argument passed in, and a function to update the state value.</p><pre>const [state, setState] = useState(initialState);</pre><p>The “setState” function can take a function as an argument, or it can also take a value to update the state.</p><pre>setState(prevState =&gt; preState - 1);</pre><pre>setState(someValue);</pre><p>No matter what, the setState function will update the target state and trigger a rerender.</p><h3>useEffect</h3><pre>useEffect(callback[, dependencies]);</pre><p>The “callback” is a callback function containing side-effect logic. It will be fired right after the completed render of this component.</p><p>The “dependencies” is an optional array of dependencies. The useEffect will execute only when the dependencies change between renderings.</p><p>Sometimes side-effects need cleanup. To do this, the callback function can return a cleanup function. There are two benefits of the clean-up process: First, the clean-up function runs before the component is removed from the UI to prevent memory leaks. Second, if the component renders multiple times, the previous side-effect is cleaned up before executing the next one.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6a874a7edeb24d0efa6a692bbbee4eac/href">https://medium.com/media/6a874a7edeb24d0efa6a692bbbee4eac/href</a></iframe><h4><strong>Best practice</strong></h4><p>In general, putting the side-effect logics in <strong>the callback function</strong>, and using <strong>the dependencies</strong> array to control when to fire the callback function.</p><p>Executing useEffect Only once right after the first render. It is like putting logic in the componentDidMount() lifecycle function.</p><pre>useEffect(() =&gt; { console.log(“some logic”); }, []);</pre><p>Executing useEffect after props or state changes. It is a replacement of componentDIdUpdate() of class-based component.</p><pre>function App() { useEffect(() =&gt; {</pre><pre><em>//Execute logic</em></pre><pre>}, [props, state]);</pre><p>Executing clean-up process before unmounting a component.</p><pre>useEffect(() =&gt; {</pre><pre><em>// Side-effect logic…</em></pre><pre><em>return</em> function cleanup() {</pre><pre><em>// Side-effect cleanup…</em></pre><pre>};</pre><pre>}, [dependencies]);</pre><h3>useContext</h3><h4>Prerequisites</h4><p>Context API allows you to pass value between components without having to explicitly pass a prop through every level of three.</p><h4>Context API in detail</h4><pre>const MyContext = React.createContext(defaultValue);</pre><p><strong>React.createContext()</strong> returns a context object that can be used across all levels of components without passing through props. The optional argument can be used as the default value when Context.Provider does not provide any value.</p><pre>&lt;MyContext.Provider value={/* some value */}&gt;</pre><p>MyContext.Provider lets wrapped components subscribe to the context. As a result, any components which subscribe to the context will re-render when the context value changes.</p><p>The Provider component accepts a value prop to be passed to consuming components that are descendants of this Provider. If it does provide the value prop, the default value provided in React.createContext will be used.</p><p>One Provider component can link to many consumer components. However, when there are multiple provider components exist, only the nearest provider will take effect.</p><pre>&lt;MyContext.Consumer&gt;<br>  {value =&gt; /* render something based on the context value */}<br>&lt;/MyContext.Consumer&gt;</pre><p>A component can subscribe to a context by wrapping itself in the context’s consumer component. The component requires a function as a child and returns a React node based on the context value.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcodesandbox.io%2Fembed%2Freverent-sunset-dlzep%3Ffile%3D%2Fsrc%2FMessage.jsx&amp;display_name=CodeSandbox&amp;url=https%3A%2F%2Fcodesandbox.io%2Fs%2Freverent-sunset-dlzep%3Ffile%3D%2Fsrc%2FMessage.jsx&amp;image=https%3A%2F%2Fcodesandbox.io%2Fapi%2Fv1%2Fsandboxes%2Fdlzep%2Fscreenshot.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=codesandbox" width="1000" height="500" frameborder="0" scrolling="no"><a href="https://medium.com/media/f394d93bae139971d37c1933682b39fb/href">https://medium.com/media/f394d93bae139971d37c1933682b39fb/href</a></iframe><h4>How useContext works</h4><p>Accepts a context object (the value returned from React.createContext) and returns the current context value for that context. The current context value is determined by the value prop of the nearest &lt;MyContext.Provider&gt; above the calling component in the tree.</p><p>When the nearest &lt;MyContext.Provider&gt; above the component updates, this Hook will trigger a rerender with the latest context value passed to that MyContext provider.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcodesandbox.io%2Fembed%2Ffsjp5&amp;display_name=CodeSandbox&amp;url=https%3A%2F%2Fcodesandbox.io%2Fs%2Ffsjp5&amp;image=https%3A%2F%2Fcodesandbox.io%2Fapi%2Fv1%2Fsandboxes%2Ffsjp5%2Fscreenshot.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=codesandbox" width="1000" height="500" frameborder="0" scrolling="no"><a href="https://medium.com/media/5653d3dc37a8342bbda02ff41ad36292/href">https://medium.com/media/5653d3dc37a8342bbda02ff41ad36292/href</a></iframe><p>The remaining ones are not very commonly used, so there is only some brief introduction. The specific details can refer to the official website documents in actual use.</p><h4>useReducer（To be continue…）</h4><h4>useCallback</h4><h4>useMemo</h4><h4>useRef</h4><p>The useRef hook helps us accessing a DOM element without causing a re-rendering of the component. The useRef hook returns a mutable object with a property “current”, whose value initialized to the passed argument. The returned ref object can be placed in the react component’s ref attribute.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e97a8325258ef59f4364d5600507cd9e/href">https://medium.com/media/e97a8325258ef59f4364d5600507cd9e/href</a></iframe><p><a href="https://levelup.gitconnected.com/understanding-useref-513b1bbe00dc">Understanding useRef</a></p><h4>useImperativeHandle</h4><h4>useLayoutEffect</h4><h4>useDebugValue</h4><h3>Rules of hooks</h3><p>Only call Hooks at the top level.</p><p>Only call Hooks from React functions</p><h3>Further reading ‘</h3><p><a href="https://reactjs.org/docs/hooks-reference.html">Hooks API Reference - React</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e202553eacc4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Debounce and Throttle]]></title>
            <link>https://wangyeux.medium.com/debounce-and-throttle-4d9cab4b6e4b?source=rss-65a29ce9d43a------2</link>
            <guid isPermaLink="false">https://medium.com/p/4d9cab4b6e4b</guid>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[WangYeUX]]></dc:creator>
            <pubDate>Fri, 19 Mar 2021 10:33:14 GMT</pubDate>
            <atom:updated>2021-03-19T10:33:40.526Z</atom:updated>
            <content:encoded><![CDATA[<p>It sounds odd, but the theory is pretty simple.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yHFv2Xwr1vqwyZISgTCVAg.jpeg" /></figure><p>Lets’s take a look at how debounce and throttle works first.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcodesandbox.io%2Fembed%2Fhardcore-cache-rw7pt%3Ffontsize%3D14%26hidenavigation%3D1%26theme%3Ddark&amp;display_name=CodeSandbox&amp;url=https%3A%2F%2Fcodesandbox.io%2Fs%2Fhardcore-cache-rw7pt%3Ffontsize%3D14%26hidenavigation%3D1%26theme%3Ddark&amp;image=https%3A%2F%2Fcodesandbox.io%2Fapi%2Fv1%2Fsandboxes%2Frw7pt%2Fscreenshot.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=codesandbox" width="1000" height="500" frameborder="0" scrolling="no"><a href="https://medium.com/media/ef0bb1b1e29bdc9b65eae5649ae5aaff/href">https://medium.com/media/ef0bb1b1e29bdc9b65eae5649ae5aaff/href</a></iframe><p>This a pretty simple realization of debounce and throttle. In the product environment, you should use Lodash or other similar strictly library.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c16f111b895ad022fe234dc41aa7b4ae/href">https://medium.com/media/c16f111b895ad022fe234dc41aa7b4ae/href</a></iframe><h3>Reference</h3><p><a href="https://codeburst.io/throttling-and-debouncing-in-javascript-b01cad5c8edf">Throttling and Debouncing in JavaScript</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4d9cab4b6e4b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[What is Webpack]]></title>
            <link>https://wangyeux.medium.com/what-is-webpack-9e866083d7f5?source=rss-65a29ce9d43a------2</link>
            <guid isPermaLink="false">https://medium.com/p/9e866083d7f5</guid>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[front-end-development]]></category>
            <category><![CDATA[webpack]]></category>
            <dc:creator><![CDATA[WangYeUX]]></dc:creator>
            <pubDate>Sun, 14 Mar 2021 17:05:22 GMT</pubDate>
            <atom:updated>2021-03-31T11:09:04.669Z</atom:updated>
            <content:encoded><![CDATA[<p>Webpack is a static module bundler. More specifically, Webpack establishes a <strong>dependency graph</strong> that consists of modules your web app needed for functioning as expected. Then, it uses this graph and configuration to generate <strong>bundles</strong>. It is made primarily for bundling JavaScript, but it can transform static assets such as HTML, CSS, and images with corresponding loaders.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QRLCpAK06MhShcNI3G8EWw.png" /><figcaption>Ref: <a href="https://webpack.js.org/">https://webpack.js.org/</a></figcaption></figure><h3>The Structure of Webpack</h3><p>Webpack’s flexibility is mainly due to its configuration file, which describes how to transform assets of the graphs and what output it should produce. The default config file named webpack.config.js, in which you can set up personalized configuration with <strong>entry, output, loaders, plugins, </strong>and<strong> mode</strong>.</p><h4>Entry</h4><p>An entry point is the beginning of Webpack’s traversal trip for building the dependency graph. Webpack can automatically find out other modules that the entry file relies on.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fb737dd1bcb4ee11a9a172a00ba746fa/href">https://medium.com/media/fb737dd1bcb4ee11a9a172a00ba746fa/href</a></iframe><h4>Output</h4><p>The output property indicates where to place the bundles it creates and how to name them. The default name for the main output file is ./dist/main.js and the path is ./dist folder.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4857e5658e6c71772caabac01adbcbca/href">https://medium.com/media/4857e5658e6c71772caabac01adbcbca/href</a></iframe><h4>Loaders</h4><p>Since the browser can only process JavaScript, CSS, and HTML files, the Webpack has to provide a way for other types of files (eg. md, txt, and so on) to be used in the browser environment. This is where loader comes into play. Loaders process and convert these particular files into valid modules that can be consumed by the environment.</p><h4>Plugins</h4><p>Plugins perform a wider range of tasks like bundle optimization, asset management, and injection of environment variables.</p><h4>Mode</h4><p>Webpack can enable build-in optimation corresponding to different models. The default model value is “production”, you can set it to either “development” or “none” also.</p><h3>Browser compatibility</h3><h3>Reference</h3><ul><li><a href="https://survivejs.com/webpack/what-is-webpack/">What is Webpack</a></li><li><a href="https://webpack.js.org/concepts/">Concepts | webpack</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9e866083d7f5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[What are XSS and CSRF]]></title>
            <link>https://wangyeux.medium.com/what-are-xss-and-csrf-5c9e1ea9437c?source=rss-65a29ce9d43a------2</link>
            <guid isPermaLink="false">https://medium.com/p/5c9e1ea9437c</guid>
            <category><![CDATA[web-security]]></category>
            <category><![CDATA[web-development]]></category>
            <dc:creator><![CDATA[WangYeUX]]></dc:creator>
            <pubDate>Fri, 12 Mar 2021 10:23:32 GMT</pubDate>
            <atom:updated>2021-04-28T06:43:23.086Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Qce8jdLSSYHIx20uIROqIQ.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@nahelabdlhadi?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Nahel Abdul Hadi</a> on <a href="https://medium.com/s/photos/hacker?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><h3>Cross-site scripting (XSS)</h3><h4>What is XSS</h4><p><a href="https://portswigger.net/web-security/cross-site-scripting">Cross-site scripting</a> (or XSS) allows an attacker to execute arbitrary JavaScript within the browser of a victim user.</p><p>There are couple of types of XSS: reflected, stored, dom-based, and mutation XSS.</p><p>First, one is reflected XSS, which simply reflected script tags in the response. The browser identifies these code as a script block and executes them.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CvIqAaLBiMoM2cda7Bf2zQ.png" /><figcaption>Reflected XSS. Reference: <a href="https://www.youtube.com/watch?v=EoaDgUgS6QA">https://www.youtube.com/watch?v=EoaDgUgS6QA</a></figcaption></figure><p>Stored XSS is similar to the reflected one but more powerful. Instead reflected in the response, it is stored in the database and gets executed by pulling it out from where it is stored. For example, you can type some script tags(&lt;script&gt;&lt;/script&gt;) in some dummy website’s comment area. And whoever sees the comment gets infected automatically.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*U9RA0BNcnm17k--ePdE0MQ.png" /><figcaption>Stored XSS. Reference: <a href="https://www.youtube.com/watch?v=EoaDgUgS6QA">https://www.youtube.com/watch?v=EoaDgUgS6QA</a></figcaption></figure><p>Dom-based XSS, which happens when the user’s input directly lands inside a dangerous part of JavaScript. The process entirely happens on the client-side.</p><p><a href="https://owasp.org/www-community/attacks/DOM_Based_XSS#:~:text=DOM%20Based%20XSS%20(or%20as,in%20an%20%E2%80%9Cunexpected%E2%80%9D%20manner.">https://owasp.org/www-community/attacks/DOM_Based_XSS#:~:text=DOM%20Based%20XSS%20(or%20as,in%20an%20%E2%80%9Cunexpected%E2%80%9D%20manner</a>.</p><p>Mutation XSS</p><h4>How XSS works</h4><p>We all know that JavaScript has access to HTML DOM, which means we can use JavaScript to manipulate DOM. Plus, having control over another site’s JavaScript can execute many malicious actions such as stealing cookies.</p><p>In short, XSS just a JavaScript injection technique. The interesting point is that the browser sees the whole response data as HTML. As a result, the input that we send out is being reflected back in response. So, we can simply add &lt;Script&gt;&lt;/Script&gt; tags in input, and the browser will start to execute these scripts when it parses the response.</p><h4>How can we prevent XSS</h4><p>Use a third-party library to sanitize JavaScript code, and spits out only clean HTML.</p><p>Popular frameworks like React, Vue, and Angular have helped deal with such problems.</p><h3>Cross-site request forgery (or CSRF)</h3><h4>What is CSRF and how it works</h4><p><a href="https://portswigger.net/web-security/csrf">Cross-site request forgery</a> (or CSRF) allows an attacker to induce a victim user to perform actions that they do not intend to. Let’s say you’ve logged in to an online bank website. And then you are lured to open a malicious web in another tab. This malicious web can forgery a request to the bank’s server to make some dangerous behaviors as cookies are sent automatically on every request you make to that domain regardless of your current domain. As a result, a forgery action happens in the context of your session.</p><h4>How can we prevent CSRF problems</h4><p>Anti CSRF token</p><p>A CSRF token is a unique, secret, unpredictable value that is generated by the server-side application and transmitted to the client in such a way that it is included in a subsequent HTTP request made by the client. When the later request is made, the server-side application validates that the request includes the expected token and rejects the request if the token is missing or invalid.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3YSaAeXFrjBx6HYPQocIVg.png" /><figcaption>Ref: <a href="https://www.youtube.com/watch?v=eWEgUcHPle0&amp;t=2s">https://www.youtube.com/watch?v=eWEgUcHPle0&amp;t=2s</a></figcaption></figure><h3>Reference:</h3><p><a href="https://portswigger.net/web-security/csrf/xss-vs-csrf#:~:text=What%20is%20the%20difference%20between,they%20do%20not%20intend%20to">XSS vs CSRF | Web Security Academy</a></p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FEoaDgUgS6QA%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DEoaDgUgS6QA&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FEoaDgUgS6QA%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/3aa97b9a1e37320147d2647530655441/href">https://medium.com/media/3aa97b9a1e37320147d2647530655441/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5c9e1ea9437c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[What is Http Cache]]></title>
            <link>https://wangyeux.medium.com/what-is-http-cache-df5961361637?source=rss-65a29ce9d43a------2</link>
            <guid isPermaLink="false">https://medium.com/p/df5961361637</guid>
            <category><![CDATA[http-request]]></category>
            <category><![CDATA[cache]]></category>
            <category><![CDATA[web-development]]></category>
            <dc:creator><![CDATA[WangYeUX]]></dc:creator>
            <pubDate>Sat, 06 Mar 2021 16:43:43 GMT</pubDate>
            <atom:updated>2021-03-31T09:00:48.104Z</atom:updated>
            <content:encoded><![CDATA[<h3>What is HTTP Cache</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QMVwbkdA6DBXq5gUUXT3Lw.jpeg" /><figcaption>We can think of HTTP cache as a warehouse where stores the copy of the previous resource. Photo by <a href="https://unsplash.com/@chuttersnap?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">CHUTTERSNAP</a> on <a href="https://unsplash.com/s/photos/warehouse?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>HTTP devices can keep copies of popular documents. Maintaining a cache of the previous resources allows the client to use a local copy of the resource, thereby eliminating unnecessary HTTP requests.</p><h3>Important HTTP headers related to the web cache</h3><p>Normally, making an HTTP cache is about three HTTP headers: Cache-control, Last-modified, and Etag. They all available in both the request header and response header.</p><ul><li>Cache-control header specifies the cache lifetime(max-age) of the resource.</li><li>Last-modified and ETag header provides a validation mechanism. Generally speaking, last-modified validate the resource with time and Etag does it with content(hash).</li></ul><p>Two things need to be born in mind:</p><p>Specifying a lifetime for each resource with Cache-control header.</p><p>Specifying a validation mechanism to allow the client to check the availability of the resource(if it expired or updated).</p><p>You should always specify both the cache lifetime and validation methods to avoid either redundant resource transfers(missing validation methods) or redundant checks(missing lifetime).</p><h4>Cache types</h4><p>Caches can be divided into two categories: <strong>private caches</strong> and <strong>shared caches</strong>.</p><p>Private cache stores resources for a single user. Web browsers have private caches build in with client-side storage.</p><p>Shared cache can be reused by more than one user. For example, a web proxy or CDN can cache resources for many users.</p><h3>How web cache works</h3><p>In general, freshness and validation decide how web cache work. Fresh resources are served directly from the cache without checking the origin server. If it is stale, the origin server will be asked to validate it.</p><h4>Fresh and stale cache</h4><p>As HTTP is a client-server protocol, serves cannot contact caches and clients when resource changes, they have to communicate an expiration time for the cache. Before expiration, the cache is fresh, after it is stale. When the stale cache receives a request, it forwards this request with an If-None-Match to check if it is still fresh. If so, the server returns a 304(Not modified) header without the body of the requested resource.</p><p>You can use Cache-Control: max-age = 3600 or Expires: Fri, 30 Oct 1998 14:19:41 GMT headers to set a freshness lifetime. When both Cache-Control and Expires are presented, Cache-Control takes precedence.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/822/1*eZhmVOf3tf-NjeIAQcvgYA.png" /><figcaption>HTTP requests in different situations. <a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Caching#private_browser_caches">https://developer.mozilla.org/en-US/docs/Web/HTTP/Caching#private_browser_caches</a></figcaption></figure><p>The freshness lifetime is calculated by several headers. If Cache-Control: max-age = n is specified, then the freshness lifetime is equal to n. If not, it checks the Expires header.</p><h4>Cache validation</h4><p>Time-based:</p><p>Response header: Last-Modified</p><p>Request header: If-Modified-Since</p><p>Content-based:</p><p>Response header: Etag</p><p>Request header: If-None-Match</p><p>The first time, the client requests a resource, and the server sends the resource back with cache headers. The second time the client requesting the same resource, if it is fresh, then the client gets the resource from the cache directly. If it is stale, the client sends a request with the header If-None-Match to the server to validate if the resource is still available. If it does, the client gets the resource from the cache and refreshes its freshness lifetime. The rules apply to Time-based validation.</p><p>If both of Last-Modified and Etag are exits, the server will check both of the headers and either return 304 or new content.</p><h3>Best practice</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vvr7kHEklGeux_o10afC9g.png" /><figcaption>Cache headers for HTTP cache</figcaption></figure><p>There are some rules for controlling how HTTP cache works. Generally, there are most common rules to be followed:</p><p>If the cache is fresh, the HTTP request sends from the browser gets a response directly from the cache without checking with the server.</p><p>If the cache is stale, the original server will be asked to validate whether the copy is still good. If it is, the server will respond with status code 304, which means “not modified”, and refresh the cache.</p><p>Under certain circumstances, for example, when it’s disconnected from the network, the stale content can be served without checking with the original server.</p><h4>Common settings of Cache-Control</h4><p>Expires and pragma headers are outdated, as a result, cache-control is mainly used in modern days.</p><p>Below are some common settings for the cache-control header:</p><p>max-age=[seconds] — specify the maximum amount of time that a cache can be considered as fresh.</p><p>private — the content can only be cached in the client and only used for the user.</p><p>public — the content can also be cached in the proxies for multiple users.</p><p>no-store — the content cannot be cached anywhere.</p><p>no-cache — the content can be cached but requires validation every time a request is reached.</p><h3>Reference:</h3><ul><li><a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Caching">HTTP caching - HTTP | MDN</a></li><li><a href="https://devcenter.heroku.com/articles/increasing-application-performance-with-http-cache-headers#:~:text=header%20based%20strategy.-,Overview,specifying%20the%20desired%20cache%20behavior">Increasing Application Performance with HTTP Cache Headers</a></li><li><a href="https://imagekit.io/blog/ultimate-guide-to-http-caching-for-static-assets/">Guide for Caching and HTTP Cache Headers for Static Content</a></li></ul><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FHiBDZgTNpXY%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DHiBDZgTNpXY&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FHiBDZgTNpXY%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/f055b442c40a4f15bd8297da7702ed34/href">https://medium.com/media/f055b442c40a4f15bd8297da7702ed34/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=df5961361637" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Redux async logic and data fetching]]></title>
            <link>https://wangyeux.medium.com/redux-async-logic-and-data-fetching-71513da4b681?source=rss-65a29ce9d43a------2</link>
            <guid isPermaLink="false">https://medium.com/p/71513da4b681</guid>
            <category><![CDATA[redux-thunk]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[asynchronous]]></category>
            <category><![CDATA[redux]]></category>
            <dc:creator><![CDATA[WangYeUX]]></dc:creator>
            <pubDate>Thu, 04 Mar 2021 07:02:28 GMT</pubDate>
            <atom:updated>2021-03-05T13:29:18.760Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AyYYoeDMTTK_7J7aCeaIUA.gif" /><figcaption>How middleware works <a href="https://redux.js.org/tutorials/essentials/part-5-async-logic">https://redux.js.org/tutorials/essentials/part-5-async-logic</a></figcaption></figure><p><strong>Middleware, a extra step where async logics run.</strong></p><p>Redux store itself don’t know anything about async logic. It only knows how to synchronously dispatch actions, update the state by calling the root reducer, and notify the ui which needs to be updated. Any asynchronicity happen outside the store.</p><p>Redux middleware, on the other side, allow you to using async logics to interact with the store. Middleware has access to <strong>dispatch</strong> and <strong>getState</strong>, which means you could write async functions in the middleware, and still has the ability to interact with the redux store by dispatching actions.</p><p>There are three concepts: the <strong>middleware</strong>, the <strong>async function</strong> and <strong>dispatch function</strong>. In sync logic, store dispatch a action. However, in the async logics, store dispatch a <strong>async function</strong> which wraps a <strong>normal dispatch</strong>.</p><p>The store dispatches a async function, which takes <strong>dispatch</strong> and <strong>getState</strong> as arguments. In the async function, it execute the async logics and then <strong>dispatch an action</strong> as same as the normal dispatch process. It is a bit convoluted, check the code below for a deeper understanding.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e137d9bc3ed41859e440a3ffdaa9048e/href">https://medium.com/media/e137d9bc3ed41859e440a3ffdaa9048e/href</a></iframe><p>There are loads of middleware for redux, the most common one is <strong>redux-thunk</strong>. As redux docs states: <em>The word “thunk” is a programming term that means </em><a href="https://en.wikipedia.org/wiki/Thunk"><em>“a piece of code that does some delayed work”</em></a><em>. </em>The thunk middleware allows us to write functions that get <strong>dispatch</strong> and <strong>getState</strong> as arguments. The thunk functions can have any async logic inside, and that logic can dispatch actions and read store state as needed.</p><p>In short, thunk function takes <strong>dispatch</strong> and <strong>getState</strong> as arguments. It processes async logics first, then dispatch a action with the data coming from the async logics. Let’s write some code to explains this process.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d59e60916bf1b61a48e7df007a2ac644/href">https://medium.com/media/d59e60916bf1b61a48e7df007a2ac644/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=71513da4b681" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>