<?xml version="1.0" encoding="UTF-8" ?>
<rss version="2.0" xmlns:content="http://purl.org/rss/1.0/modules/content/">
<channel>
<title>undefined</title>
<link>http://irenaapp.de/</link>
<description>Web developer and Linguist. This is my digital notebook.</description>
<item>
<title><![CDATA[Containerizing React Apps: A Docker Deep Dive]]></title>
<link>http://irenaapp.de//blog-app-testing/</link>
<guid>http://irenaapp.de//blog-app-testing/</guid>
<pubDate>Fri, 13 Feb 2026 14:37:00 GMT</pubDate>
<description><![CDATA[Why containerize a React app Containerization solves a common problem in frontend teams: "works on my machine". A container bundles the app…]]></description>
<content:encoded><![CDATA[<h2>Why containerize a React app</h2>
<p>Containerization solves a common problem in frontend teams: "works on my machine". A container bundles the app, build tools, and system dependencies into a single unit. That means:</p>
<ul>
<li>Repeatable builds across machines</li>
<li>Consistent Node and system libraries</li>
<li>CI builds that match production output</li>
<li>Clear separation between dev and prod workflows</li>
</ul>
<h2>The two images you actually need</h2>
<p>Most React/Gatsby projects benefit from two images:</p>
<ol>
<li><strong>Development image</strong>: fast feedback, hot reload</li>
<li><strong>Production image</strong>: minimal, static assets served by a web server</li>
</ol>
<p>This is the core of a modern frontend DevOps flow. A single Dockerfile can contain both using multi-stage builds.</p>
<h2>A production-first Dockerfile</h2>
<p>A typical multi-stage Dockerfile looks like this:</p>
<pre><code class="language-Dockerfile"># syntax=docker/dockerfile:1
FROM node:18-bullseye-slim AS base
WORKDIR /app
ENV NODE_ENV=production
FROM base AS deps
COPY package.json package-lock.json ./
RUN npm ci
FROM base AS dev
ENV NODE_ENV=development
COPY --from=deps /app/node_modules ./node_modules
COPY . .
EXPOSE 8000
CMD ["npm", "run", "develop", "--", "-H", "0.0.0.0", "-p", "8000"]
FROM base AS build
COPY --from=deps /app/node_modules ./node_modules
COPY . .
RUN npm run build
FROM nginx:alpine AS prod
COPY --from=build /app/public /usr/share/nginx/html
EXPOSE 80
CMD ["nginx", "-g", "daemon off;"]
</code></pre>
<p>What this gives you:</p>
<ul>
<li><strong>dev stage</strong> for local iteration</li>
<li><strong>build stage</strong> for compiling static assets</li>
<li><strong>prod stage</strong> for fast, minimal serving</li>
</ul>
<h2>Dev vs prod behavior</h2>
<p><strong>Development</strong>:</p>
<ul>
<li>Runs your framework dev server</li>
<li>Hot reload and source maps</li>
<li>Larger image with all tooling</li>
</ul>
<p><strong>Production</strong>:</p>
<ul>
<li>Static build output</li>
<li>Minimal runtime image (nginx)</li>
<li>Faster startup and lower memory</li>
</ul>
<p>This separation is what makes CI/CD predictable.</p>
<h2>CI decisions: build, test, or skip</h2>
<p>A smart pipeline does not run full tests for every change. You can implement a small impact analyzer that checks what changed and decides what to run.</p>
<p>Example rules:</p>
<ul>
<li><code>content/</code> or <code>.md</code> -> build only</li>
<li><code>src/</code> or <code>gatsby-*.js</code> -> build + test</li>
<li><code>k8s/</code> or <code>netlify/</code> -> deploy pipeline only</li>
</ul>
<p>This keeps pipelines fast without losing safety.</p>
<h2>What happens in Kubernetes</h2>
<p>When you deploy a frontend container to Kubernetes, you are usually deploying a static site image:</p>
<ul>
<li>A <strong>Deployment</strong> runs the container</li>
<li>A <strong>Service</strong> exposes port 80</li>
<li>An <strong>Ingress</strong> can route your domain to the service</li>
</ul>
<p>Because the image is static, scaling it is cheap. You can run multiple replicas without extra complexity.</p>
<h2>Common pitfalls and fixes</h2>
<ul>
<li><strong>Missing static files</strong>: ensure the build output directory is correct</li>
<li><strong>Large images</strong>: use multi-stage builds to keep prod images small</li>
<li><strong>Cache issues</strong>: pin Node version and use <code>npm ci</code></li>
<li><strong>Port confusion</strong>: dev servers usually run on 3000/8000, prod uses 80</li>
</ul>
<h2>A simple local workflow</h2>
<ul>
<li>Dev: <code>docker compose up --build blog-dev</code></li>
<li>Prod: <code>docker compose up --build blog-prod</code></li>
<li>K8s: build image, load into kind, apply YAML, port-forward</li>
</ul>
<h2>Takeaway</h2>
<p>Containerization is not just packaging. It is a discipline that makes frontend delivery reliable. Once your Dockerfile is solid and your CI can decide what to run, you have a scalable DevOps workflow that teams can trust.</p>]]></content:encoded>
</item>
<item>
<title><![CDATA[React Impact Scope: Tracking Gatsby Change Impact at Scale]]></title>
<link>http://irenaapp.de//blog-react-impact-scope/</link>
<guid>http://irenaapp.de//blog-react-impact-scope/</guid>
<pubDate>Fri, 06 Feb 2026 09:00:00 GMT</pubDate>
<description><![CDATA[React Impact Scope: Tracking Gatsby Change Impact The tool I am building is designed to make complex systems predictable. When the surface…]]></description>
<content:encoded><![CDATA[<h2>React Impact Scope: Tracking Gatsby Change Impact</h2>
<p>The tool I am building is designed to make complex systems predictable. When the surface area grows, clarity becomes a performance feature. This post is a focused look at how I’m reducing Gatsby change risk with a practical impact-analysis workflow.</p>
<p>React encourages small, composable components, and Gatsby layers a powerful data system on top of that simplicity. The combination is productive, but it can also blur the lines between what is “just a component” and what is effectively a build‑time dependency. A change in a page file, a shared layout, or a GraphQL query can cascade through the site in ways that are not obvious from imports alone, especially once data sourcing and build artifacts come into play.</p>
<p>I am building <strong>react-impact</strong>, a lightweight CLI that answers a simple but powerful question for Gatsby projects:</p>
<p><strong>If I change this file, what else is impacted?</strong></p>
<p>As Gatsby sites grow, small edits can ripple across pages, layouts, and data modules. This post captures what the tool does today, what it is testing, and which Gatsby-specific issues it is designed to solve next.</p>
<h2>What the Tool Does Today</h2>
<p>react-impact currently:</p>
<ul>
<li>Scans a project and builds a file-level dependency graph</li>
<li>Supports JavaScript and TypeScript (<code>.js</code>, <code>.jsx</code>, <code>.ts</code>, <code>.tsx</code>)</li>
<li>Reports <code>dependencies</code>, <code>dependents</code>, and <code>affectedComponents</code></li>
<li>Includes change-set mode to focus on impacted files only</li>
<li>Skips noisy generated folders by default (<code>.cache</code>, <code>public</code>, <code>node_modules</code>, etc.)</li>
<li>Supports per-project ignore rules via <code>.react-impactignore</code></li>
</ul>
<h2>Example: Change-Set Mode</h2>
<pre><code class="language-bash">node react-impact/src/cli.js analyze . --changed src/pages/index.js --format text
</code></pre>
<p>Output:</p>
<pre><code>Impacted files: 2 (changed: 1, dependents: 1)
Changed:
src/pages/index.js | deps:13 | dependents:1
Impacted:
src/app.js | deps:18 | dependents:0
</code></pre>
<h2>What It’s Testing Right Now</h2>
<p>The tool has automated tests for:</p>
<ul>
<li>File scanning behavior</li>
<li>Dependency graph building</li>
<li>CLI output formats</li>
<li>Change-set filtering</li>
</ul>
<p>Both Jest and Mocha are configured so the CLI and core utilities can be validated quickly.</p>
<h2>The Gatsby Issue It Already Solves</h2>
<p>In Gatsby, the <code>.cache</code> directory can explode in size and drown the real signal. react-impact now skips that by default, and allows project-specific ignores so scanning stays focused and fast.</p>
<p>Gatsby can also feel unpredictable when GraphQL queries, page creation, and data sourcing are involved. A small change in a query or a shared fragment can reshape data downstream without any obvious import path changes, and React’s component tree may re-render in places that are not immediately visible in the code. This is where impact analysis becomes critical: it helps surface the hidden coupling between data, pages, and components, so you can see what is actually affected before running a full build.</p>
<h2>What I’m Planning Next (Gatsby Focus)</h2>
<p>Here is the next set of improvements I want to ship:</p>
<ul>
<li>Glob-pattern ignore rules for more precise filtering</li>
<li>Change-set input directly from Git</li>
<li>Smarter component-level impact, not just file-level</li>
<li>Gatsby-aware page detection from <code>src/pages</code></li>
</ul>
<p>I am keeping the roadmap structured across four pillars so the work stays focused and measurable. Each pillar captures a specific kind of progress: core accuracy, daily usability, engineering quality, and deployment readiness.</p>
<h2>Core Product</h2>
<p>The core is about correctness: the tool must interpret real projects the way developers actually structure them. These are the foundations I will continue to harden so impact analysis stays reliable as projects scale.</p>
<ul>
<li>TypeScript support (<code>.ts</code>/<code>.tsx</code> scanning + parsing)</li>
<li>Ignore config file (e.g., <code>.react-impactignore</code>)</li>
<li>JSON report output (<code>--output report.json</code>)</li>
<li>Change‑set mode (given a list of changed files, compute impacted files/components)</li>
</ul>
<h2>Usability</h2>
<p>Even the best analysis is only valuable if it is easy to run and easy to interpret. These upgrades focus on making react-impact feel natural in a developer’s daily workflow.</p>
<ul>
<li>Better CLI UX (help, version, and flags via <code>commander</code> or <code>yargs</code>)</li>
<li>Readable report (table or tree output)</li>
<li>Config file (<code>react-impact.config.js</code>) to customize roots/excludes</li>
</ul>
<h2>Engineering Quality</h2>
<p>If this is going to be trusted in CI, it needs to be boringly reliable. These items focus on stability, coverage, and long-term maintainability.</p>
<ul>
<li>More tests (edge cases, symlinks, mixed imports)</li>
<li>CI badges in README</li>
<li>NPM packaging (<code>bin</code>, <code>publishConfig</code>, versioning)</li>
</ul>
<h2>Docker/K8s</h2>
<p>This is where the tool becomes plug-and-play in real pipelines. The goal is to make impact analysis cheap, repeatable, and easy to automate.</p>
<ul>
<li>Multi‑stage Dockerfile (smaller image)</li>
<li>Docker entrypoint flags</li>
<li>Optional API wrapper (for K8s later)</li>
</ul>
<h2>Why I’m Building This</h2>
<p>I want confidence that small changes to my Gatsby blog won’t cause hidden breakage elsewhere. react-impact gives me that clarity before I run a full build or deploy.</p>
<p>I’ll update this post as the tool evolves.</p>]]></content:encoded>
</item>
<item>
<title><![CDATA[How Docker Works: A Deep Dive Into the Local Workflow]]></title>
<link>http://irenaapp.de//blog-docker-workflow-deep-dive/</link>
<guid>http://irenaapp.de//blog-docker-workflow-deep-dive/</guid>
<pubDate>Thu, 05 Feb 2026 19:40:00 GMT</pubDate>
<description><![CDATA[The Docker workflow, end‑to‑end Docker feels simple when you run docker build and docker run, but the workflow underneath is a disciplined…]]></description>
<content:encoded><![CDATA[<h2>The Docker workflow, end‑to‑end</h2>
<p>Docker feels simple when you run <code>docker build</code> and <code>docker run</code>, but the workflow underneath is a disciplined lifecycle: <strong>define → build → run → iterate → publish</strong>. Understanding that loop helps you debug faster, design cleaner images, and keep your environments consistent across teams.</p>
<p>This post breaks down the full local workflow from Dockerfile to registry.</p>
<h2>Step 1: Dockerfile as the build contract</h2>
<p>The Dockerfile is not just a script; it is a <strong>contract</strong> that describes your application’s runtime environment. It tells Docker which base image to use, how to install dependencies, what files to copy, and how to start the app. Every instruction produces an immutable layer, and the final result is your image.</p>
<p>Key idea: if it is not in the Dockerfile, it is not reproducible.</p>
<h2>Step 2: Build the image</h2>
<p>When you run <code>docker build</code>, Docker executes the Dockerfile line by line and creates an image. That image is a <strong>frozen artifact</strong>: it contains your app, its dependencies, and a minimal OS layer.</p>
<p>A good image is:</p>
<ul>
<li>deterministic (same Dockerfile → same output),</li>
<li>cache‑friendly (stable layers first),</li>
<li>and portable (runs the same on any Docker host).</li>
</ul>
<h2>Step 3: Run the container</h2>
<p>Running an image creates a container, which is a <strong>runtime instance</strong> of that image. The container adds a writable layer on top of the image, which means you can interact with it, change files, install packages, and run processes.</p>
<p>Important distinction:</p>
<ul>
<li>The <strong>image is immutable</strong>.</li>
<li>The <strong>container is mutable but disposable</strong>.</li>
</ul>
<p>This is why containers can be started, stopped, restarted, and replaced without changing the underlying image.</p>
<h2>Step 4: Operate the container lifecycle</h2>
<p>Containers are managed like lightweight processes:</p>
<ul>
<li>Start: <code>docker start</code></li>
<li>Stop: <code>docker stop</code></li>
<li>Restart: <code>docker restart</code></li>
</ul>
<p>This makes containers ideal for repeatable environments: you can tear them down and spin them back up without re‑installing dependencies or re‑configuring the OS.</p>
<h2>Step 5: Commit changes (when you must)</h2>
<p>Sometimes you make manual changes inside a running container: install a tool, tweak a config, or debug something interactive. Docker lets you <code>commit</code> that container into a new image.</p>
<p>This is a <strong>valid technique</strong>, but not a best practice for production. The best practice is to codify those changes in the Dockerfile so the build remains reproducible. Use <code>commit</code> for exploration, but convert successful changes back into the Dockerfile.</p>
<h2>Step 6: Push to a registry</h2>
<p>Once you have a stable image, the next step is distribution. Registries (like Docker Hub or a private registry) are where you publish images so others can pull and run them.</p>
<p>Typical flow:</p>
<ul>
<li><code>docker tag</code> → add registry and version metadata</li>
<li><code>docker push</code> → publish the image</li>
<li><code>docker pull</code> → retrieve it on another machine</li>
</ul>
<p>This is how the same image can run on your laptop, in CI, and in production with zero drift.</p>
<h2>The workflow in one line</h2>
<p><strong>Dockerfile → build image → run container → iterate → commit (optional) → push → pull → run.</strong></p>
<p>If you hold this loop in your head, the rest of Docker becomes significantly less mysterious.</p>
<h2>Production‑minded takeaways</h2>
<ul>
<li>Treat the Dockerfile as the source of truth.</li>
<li>Keep containers disposable and state external.</li>
<li>Avoid manual changes that can’t be reproduced.</li>
<li>Push only versioned, traceable images.</li>
</ul>
<p>That is the core discipline behind reliable container workflows.</p>]]></content:encoded>
</item>
<item>
<title><![CDATA[Docker Compose: Tradeoffs, Failure Modes, and Production Caveats]]></title>
<link>http://irenaapp.de//blog-docker-compose-perspective/</link>
<guid>http://irenaapp.de//blog-docker-compose-perspective/</guid>
<pubDate>Thu, 05 Feb 2026 18:35:00 GMT</pubDate>
<description><![CDATA[Compose in the architecture: what it is and what it is not Docker Compose is a local and single‑host orchestration tool, not a production…]]></description>
<content:encoded><![CDATA[<h2>Compose in the architecture: what it is and what it is not</h2>
<p>Docker Compose is a <strong>local and single‑host orchestration tool</strong>, not a production control plane. Its job is to make multi‑service development and testing repeatable by defining services, networks, and volumes in a declarative file. It does not provide multi‑node scheduling, autoscaling, or policy enforcement. A useful mental model is to treat Compose as the <strong>assembly script</strong> for a stack, not the runtime substrate for a distributed system.</p>
<h2>Tradeoffs you accept when choosing Compose</h2>
<p>Compose optimizes for simplicity and developer velocity. In exchange, you give up production‑grade capabilities like dynamic scheduling, traffic shaping, progressive delivery, and strong isolation boundaries. Compose also assumes a single host, which means failure domains are tightly coupled: if that host goes down, the entire stack is gone. These are acceptable tradeoffs for local dev and CI previews, but not for customer‑facing workloads.</p>
<h2>Failure modes that show up in real teams</h2>
<p>The most common failure mode is <strong>state entanglement</strong>: a container is rebuilt, but state lives in a volume that is not versioned or migrated. Another is <strong>network ambiguity</strong>, where service discovery is assumed to be stable but containers are removed and recreated with different runtime configurations. Teams also run into <strong>configuration drift</strong> when environment variables or bind mounts differ across machines. Compose makes the stack easy to start, but it does not guarantee that two developers have identical environments unless you are disciplined about configuration and dependencies.</p>
<h2>Production caveats you should state explicitly</h2>
<p>If a stack requires predictable uptime, zero‑downtime deploys, secret rotation, or policy‑driven access controls, Compose is the wrong tool. It lacks native constructs for rollout strategies, distributed health checks, and multi‑tenant governance. Stateful services also need care: volumes are local to the host and do not solve replication, backup, or disaster recovery. In a production context, Compose should be treated as a <strong>transitional tool</strong> or a development scaffold, not the final runtime.</p>
<h2>The takeaway</h2>
<p>Compose is excellent for making a system easy to run, but it is not built to keep that system <strong>highly available, secure, and scalable</strong> under real‑world conditions. The right stance is to use Compose deliberately for local or ephemeral stacks and to move to a true orchestrator or managed platform once operational requirements grow beyond a single host.</p>]]></content:encoded>
</item>
<item>
<title><![CDATA[Docker Architecture: A Deep Dive]]></title>
<link>http://irenaapp.de//blog-docker-architecture-deep-dive/</link>
<guid>http://irenaapp.de//blog-docker-architecture-deep-dive/</guid>
<pubDate>Thu, 05 Feb 2026 17:10:00 GMT</pubDate>
<description><![CDATA[What Is a Container? You can think of a software container as a container in the real world. The idea is to put your application and its…]]></description>
<content:encoded><![CDATA[<h2>What Is a Container?</h2>
<p>You can think of a software container as a container in the real world. The idea is to put your application and its dependencies inside of an encapsulated container. This way, you isolate the application from other applications on your host system. While this may not seem beneficial for a moment, the isolation of dependencies is a strong feature. Hence, it is also one of the major reasons for using containers.</p>
<p>Imagine you had two applications. Both have various third-party libraries they depend upon. However, both share a common dependency. The problem? They depend on different versions of the same library!</p>
<p>Different programming languages and frameworks have various solutions for this kind of problem, but there are cases where such a solution does not exist out-of-the-box. Welcome to the world of containers, where you achieve exactly that!</p>
<p>But this is not the only advantage of containers, though one of the major ones. Furthermore, you can scale containers easily. Do you have a website, which gets a bunch of requests, is optimised in many ways but still cannot handle all these requests? Spawn a second container, so (roughly) twice as much requests can be handled!</p>
<h2>Why Docker architecture matters</h2>
<p>Docker feels simple on the surface: <code>docker build</code>, <code>docker run</code>, done. Underneath, there is a well‑designed stack that explains <strong>why</strong> it is fast, portable, and reliable. If you understand that stack, you can debug faster, optimize images, and make better infrastructure decisions.</p>
<p>This deep dive walks through Docker’s architecture in layers, from the CLI to the kernel.</p>
<h2>The high‑level architecture (three core pieces)</h2>
<p>Docker is a client‑server system with three essential components:</p>
<ul>
<li><strong>Docker Client</strong>: the CLI (<code>docker</code>) and REST API client.</li>
<li><strong>Docker Daemon</strong> (<code>dockerd</code>): the server that builds images, runs containers, manages networks/volumes.</li>
<li><strong>Container Runtime</strong>: the low‑level engine that actually starts containers.</li>
</ul>
<p>When you run a command, the client sends an API request to the daemon. The daemon schedules the action and hands off execution to the runtime.</p>
<h2>Docker Client: the API front door</h2>
<p>The Docker client is thin by design. It does not do the heavy lifting; it delegates everything to the daemon over a REST API.</p>
<p>Key points:</p>
<ul>
<li>The daemon can be local or remote.</li>
<li>Every CLI command maps to an API call.</li>
<li>Authentication and TLS matter when the daemon is remote.</li>
</ul>
<p>This is why Docker feels consistent across environments: the client is just the frontend.</p>
<h2>Docker Daemon (<code>dockerd</code>): the control plane</h2>
<p><code>dockerd</code> is the brain. It manages state and orchestrates actions.</p>
<p>Responsibilities:</p>
<ul>
<li>Build images and store them in the local image store.</li>
<li>Create, start, stop, and remove containers.</li>
<li>Manage networks, volumes, and plugins.</li>
<li>Expose the API for tooling (Docker CLI, Compose, CI systems).</li>
</ul>
<p>When you see a Docker issue, <strong>dockerd logs</strong> are often the first place to look.</p>
<h2>containerd and runc: the runtime chain</h2>
<p>Docker does not start containers directly. It delegates to a lower‑level runtime stack:</p>
<ul>
<li><strong>containerd</strong>: a container lifecycle manager (pulls images, manages snapshots, runs containers).</li>
<li><strong>runc</strong>: the low‑level runtime that creates containers using Linux primitives.</li>
</ul>
<p>This layered design is why Docker integrates with Kubernetes and other tools that also speak containerd.</p>
<h2>The Linux kernel features behind containers</h2>
<p>Containers are not lightweight VMs. They are Linux processes isolated by kernel features:</p>
<ul>
<li><strong>Namespaces</strong>: isolate process trees, network stacks, mounts, users, and IPC.</li>
<li><strong>cgroups</strong>: enforce resource limits (CPU, memory, I/O).</li>
<li><strong>Union/overlay filesystems</strong>: combine read‑only image layers with a writable container layer.</li>
</ul>
<p>Docker orchestrates these kernel primitives so you don’t have to.</p>
<h2>Image architecture: layers and immutability</h2>
<p>Images are built as <strong>ordered layers</strong>. Each <code>Dockerfile</code> instruction creates a new layer.</p>
<p>Key facts:</p>
<ul>
<li>Layers are immutable and cached.</li>
<li>Multiple images can share the same base layers.</li>
<li>Containers add a <strong>writable top layer</strong> for runtime changes.</li>
</ul>
<p>This is why small, well‑ordered Dockerfiles build faster and reuse cache effectively.</p>
<h2>Build pipeline: from Dockerfile to image</h2>
<p>A typical build pipeline:</p>
<ol>
<li>Dockerfile is parsed.</li>
<li>Each instruction produces a filesystem layer.</li>
<li>Metadata (entrypoint, env vars, labels) is stored in the image config.</li>
<li>The final image is saved in the local image store.</li>
</ol>
<p>Modern builds often use <strong>BuildKit</strong> for parallelism, smarter caching, and secrets handling.</p>
<h2>Storage drivers: how image layers are stored</h2>
<p>Docker uses a <strong>storage driver</strong> (like <code>overlay2</code>) to manage image layers.</p>
<p>Why it matters:</p>
<ul>
<li>It affects performance and disk usage.</li>
<li>It determines how layers are merged at runtime.</li>
<li>It impacts copy‑on‑write behavior.</li>
</ul>
<p>On Linux, <code>overlay2</code> is the default because it is fast and efficient.</p>
<h2>Networking architecture</h2>
<p>Docker provides multiple network modes:</p>
<ul>
<li><strong>bridge</strong> (default): containers get a private network with NAT.</li>
<li><strong>host</strong>: container shares the host network stack.</li>
<li><strong>none</strong>: no network.</li>
<li><strong>overlay</strong>: multi‑host networking (Swarm/Kubernetes).</li>
</ul>
<p>Under the hood, Docker uses Linux networking primitives like veth pairs, bridges, and iptables rules.</p>
<h2>Volumes and bind mounts</h2>
<p>Containers are disposable; data should not be.</p>
<ul>
<li><strong>Volumes</strong>: managed by Docker, portable, and recommended for stateful data.</li>
<li><strong>Bind mounts</strong>: map a host path directly into a container.</li>
</ul>
<p>Volumes are preferred in production because they are portable and less error‑prone.</p>
<h2>Container lifecycle (what really happens on <code>docker run</code>)</h2>
<ol>
<li>Docker client sends <code>POST /containers/create</code>.</li>
<li><code>dockerd</code> resolves the image, config, and resources.</li>
<li>containerd pulls the image if needed.</li>
<li>runc creates namespaces/cgroups and starts the process.</li>
<li>The container gets a writable layer on top of the image.</li>
</ol>
<p>This chain explains common issues like pull failures, permission problems, and resource limits.</p>
<h2>Security model</h2>
<p>Docker’s security comes from isolation, but it is not a VM boundary.</p>
<p>Key practices:</p>
<ul>
<li>Run as non‑root inside containers.</li>
<li>Use minimal base images.</li>
<li>Scan images for vulnerabilities.</li>
<li>Restrict capabilities and mount permissions.</li>
</ul>
<p>Docker gives you the tools; you still need to apply them.</p>
<h2>Architecture diagram (mental model)</h2>
<p><img src="/images/engine-components-flow.png" alt="alt text">
<em>Docker Engine components flow (official documentation).</em></p>
<p>This is the core execution path for every container.</p>
<h2>Practical takeaways</h2>
<ul>
<li>Docker is a <strong>client‑server system</strong>, not a single binary.</li>
<li>Containers are <strong>Linux processes</strong>, isolated by kernel features.</li>
<li>Images are <strong>layered filesystems</strong>, optimized for reuse and caching.</li>
<li>The runtime stack (containerd + runc) is the bridge between Docker and the OS.</li>
</ul>
<p>Once you know these internals, troubleshooting feels far less mysterious.</p>
<h2>Next steps</h2>
<p>If you want to go deeper, explore:</p>
<ul>
<li><code>docker info</code> (storage driver, cgroup version)</li>
<li><code>docker system df</code> (image and layer disk usage)</li>
<li><code>docker inspect <container></code> (runtime config)</li>
</ul>]]></content:encoded>
</item>
<item>
<title><![CDATA[Docker Essentials: Managing Dependencies With Ease]]></title>
<link>http://irenaapp.de//blog-docker-essentials-managing-dependencies/</link>
<guid>http://irenaapp.de//blog-docker-essentials-managing-dependencies/</guid>
<pubDate>Thu, 05 Feb 2026 16:30:00 GMT</pubDate>
<description><![CDATA[The problem Docker quietly solves The most common developer pain I see isn’t “how do I write the code?” It’s “how do I run the code the same…]]></description>
<content:encoded><![CDATA[<h2>The problem Docker quietly solves</h2>
<p>The most common developer pain I see isn’t “how do I write the code?” It’s <strong>“how do I run the code the same way everywhere?”</strong></p>
<p>Dependencies drift. One teammate has Node 18, another has Node 20. Your machine has a newer Python, the CI runner has an older one. You try to recreate a production bug, but your local environment is subtly different. Everything works <strong>until it doesn’t</strong>.</p>
<p>Docker fixes this by packaging your app <strong>and its dependencies</strong> into a single, portable unit: a container. That unit runs the same on your laptop, in CI, and on a server. If you can run it in Docker, you can run it anywhere Docker exists.</p>
<p><img src="/images/docker6.png" alt="Docker containers">
<em>Docker makes environments predictable and portable.</em></p>
<h2>The key mental model</h2>
<ul>
<li>An <strong>image</strong> is the recipe: immutable, reusable, shareable.</li>
<li>A <strong>container</strong> is the running instance: an image + runtime state.</li>
</ul>
<p>You build images. You run containers.</p>
<p>Once that clicks, the rest is mechanics.</p>
<h2>A tiny Dockerfile that solves real problems</h2>
<p>Here’s the smallest useful Dockerfile for a Node app:</p>
<pre><code class="language-Dockerfile">FROM node:20-slim
WORKDIR /app
COPY package.json package-lock.json ./
RUN npm ci --omit=dev
COPY . .
CMD ["node", "server.js"]
</code></pre>
<p>Why this works well:</p>
<ul>
<li>It locks dependencies via <code>package-lock.json</code>.</li>
<li>It installs only production deps for a smaller image.</li>
<li>It provides a clean, repeatable runtime.</li>
</ul>
<p>Now you can build and run it anywhere:</p>
<pre><code class="language-bash">docker build -t my-app .
docker run --rm -p 3000:3000 my-app
</code></pre>
<p>Same app. Same dependencies. Every time.</p>
<h2>When you need multiple services</h2>
<p>Most real projects include at least two moving parts: an app and a database. Docker Compose gives you a simple way to define them together.</p>
<p>Example <code>docker-compose.yml</code>:</p>
<pre><code class="language-yaml">services:
app:
build: .
ports:
- "3000:3000"
environment:
- DATABASE_URL=postgres://postgres:postgres@db:5432/app
depends_on:
- db
db:
image: postgres:16
environment:
- POSTGRES_PASSWORD=postgres
volumes:
- db_data:/var/lib/postgresql/data
volumes:
db_data:
</code></pre>
<p>Bring it up with:</p>
<pre><code class="language-bash">docker compose up --build
</code></pre>
<p>This gives you a reproducible stack you can share with teammates or CI without a README full of setup steps.</p>
<h2>Volumes: keep data when containers restart</h2>
<p>Containers are disposable by design. If you want your database (or any state) to persist, use volumes. In Compose, that’s the <code>volumes:</code> block. No volume means <strong>data disappears</strong> when the container is removed.</p>
<p>A quick rule:</p>
<ul>
<li><strong>Use volumes</strong> for databases, uploads, and caches you want to persist.</li>
<li><strong>Avoid volumes</strong> when you want clean, repeatable state (tests, CI).</li>
</ul>
<h2>Dependency management patterns that scale</h2>
<p>These are habits that make Docker “boringly reliable”:</p>
<ul>
<li><strong>Pin your base images</strong> (e.g., <code>node:20.11-slim</code>, not <code>node:latest</code>).</li>
<li><strong>Use <code>npm ci</code> or <code>pip install --requirement</code></strong> so dependency sets are deterministic.</li>
<li><strong>Split build and runtime stages</strong> to keep images small.</li>
<li><strong>Copy lockfiles first</strong> so dependency layers are cached.</li>
<li><strong>Use <code>.dockerignore</code></strong> to avoid shipping <code>node_modules</code>, build artifacts, and secrets.</li>
</ul>
<h2>Common pitfalls (and quick fixes)</h2>
<ul>
<li>
<p><strong>“It works on my machine.”</strong>
Fix: run it in the container, not on the host.</p>
</li>
<li>
<p><strong>Huge images.</strong>
Fix: use slim base images and multi‑stage builds.</p>
</li>
<li>
<p><strong>Slow builds.</strong>
Fix: copy lockfiles first, keep the dependency layer cached.</p>
</li>
<li>
<p><strong>Ports don’t work.</strong>
Fix: remember <code>-p host:container</code> and confirm the app binds to <code>0.0.0.0</code>.</p>
</li>
</ul>
<h2>A gentle way to start today</h2>
<p>If you’re new to Docker, start small:</p>
<ol>
<li>Containerize one app.</li>
<li>Add a single dependency (like Postgres) with Compose.</li>
<li>Treat your Dockerfile as the source of truth for running the app.</li>
</ol>
<p>Within a day, you’ll notice a difference: fewer setup issues, fewer “works for me” surprises, and a more confident path to production.</p>
<p>Docker doesn’t just simplify deployments — it <strong>stabilizes your development environment</strong>. That’s the real win.</p>]]></content:encoded>
</item>
<item>
<title><![CDATA[Testing My Blog with Docker and Kind]]></title>
<link>http://irenaapp.de//blog-docker-kind-testing/</link>
<guid>http://irenaapp.de//blog-docker-kind-testing/</guid>
<pubDate>Thu, 05 Feb 2026 14:55:00 GMT</pubDate>
<description><![CDATA[Why I did this My blog already builds on push, but I wanted a repeatable, production‑like workflow I can test locally. Docker and Kubernetes…]]></description>
<content:encoded><![CDATA[<h2>Why I did this</h2>
<p>My blog already builds on push, but I wanted a <strong>repeatable, production‑like workflow</strong> I can test locally. Docker and Kubernetes are perfect for this. The goal: make sure my Gatsby build behaves the same on my laptop and in CI, and that I can deploy a static image to a cluster with confidence.</p>
<p><img src="/images/docker6.png" alt="Docker + Kubernetes workflow">
<em>My local Docker + kind testing workflow.</em></p>
<p>The core problem I’m trying to solve is that modern frontend CI pipelines treat every change as if it were equally risky, and that’s almost never true. In a React or Gatsby project, a tiny Markdown edit, a style tweak, and a dependency upgrade all trigger the same expensive steps: full builds, test suites, and sometimes even deploys. The result is wasted compute, slower feedback loops, and a team that waits on a pipeline that isn’t actually giving them more safety. My idea is to build a small analyzer that reads the git diff, maps changed files to impact areas (content, UI, config, infrastructure), and emits a short JSON payload that the CI pipeline can use to decide what to do. If the only change is in content/, it should build but skip tests; if src/ or gatsby-*.js changes, it should build and test; if k8s/ or deployment config changes, it should trigger infrastructure checks. This tiny piece of metadata becomes a decision engine that makes CI smarter, faster, and more intentional without reducing reliability, the pipeline does less work when it should, and more work when it must. If we get it right, it shifts the mindset from “always run everything” to “run what matters,” which is the difference between a pipeline that feels heavy and one that feels sharp.</p>
<h2>The technical problem</h2>
<p>In practice, frontend CI pipelines are usually wired around a single heuristic: “if anything changed, run everything.” That means a Gatsby site rebuilds even when the only diff is in a Markdown file, and test suites run even if you just update images or copy. The pipeline cannot distinguish between changes in content/, src/, gatsby-config.js, or k8s/ and therefore treats low‑risk and high‑risk edits identically. This is especially expensive for static‑site builds because they tend to be CPU‑intensive, and for test suites that spin up browsers or mock servers. The root cause is not the CI system itself; it’s the missing decision layer. There is no structured metadata that says “this change affects rendering but not behavior,” or “this change only affects deployment manifests.” Without that layer, the pipeline can’t optimize.</p>
<h2>My fix</h2>
<p>My solution is a small CLI that reads the git diff, classifies each changed file into impact domains, and emits a machine‑readable summary like { changedAreas, shouldBuild, shouldTest, shouldDeploy }. The classification rules are deterministic and traceable: content/** and .md map to “content”; src/** or .jsx/.tsx map to “ui”; gatsby-config.js, package.json, or lockfiles map to “config”; k8s/**, netlify.toml, or CI YAML files map to “infrastructure.” The output becomes a contract for CI steps: build only when shouldBuild is true, run tests only when UI or config changed, and trigger deployment only when infrastructure or build artifacts changed. Over time, this can be refined with an allow‑list and overrides, but the first version already cuts wasted runs while keeping risk under control. The key is that the tool doesn’t replace CI logic, it feeds CI a clear signal so the pipeline becomes conditional, reproducible, and fast.</p>
<p>My guide is the full walkthrough I used to get there with my solution.</p>
<h2>Step 1 — Install Docker Desktop (macOS)</h2>
<p>I installed Docker Desktop for Apple Silicon (arm64). Once installed, I started it and verified the daemon:</p>
<pre><code class="language-bash">docker info
</code></pre>
<p>If Docker is running, <code>docker info</code> returns server details (containers, images, runtime, etc.). That’s your green light.</p>
<h2>Step 2 — Containerize the Gatsby blog</h2>
<p>I created a multi‑stage Dockerfile:</p>
<ul>
<li><strong>dev</strong> stage: runs <code>gatsby develop</code> for hot reload</li>
<li><strong>build</strong> stage: runs <code>gatsby build</code></li>
<li><strong>prod</strong> stage: serves the static output with nginx</li>
</ul>
<p>Then I added <code>docker-compose.yml</code> with two services:</p>
<ul>
<li><code>blog-dev</code> (port 8000)</li>
<li><code>blog-prod</code> (port 8080)</li>
</ul>
<p>To test production output locally:</p>
<pre><code class="language-bash">docker compose up --build blog-prod
</code></pre>
<p>Open <code>http://localhost:8080</code> and you should see the static build.</p>
<h2>Step 3 — Create a local Kubernetes cluster with kind</h2>
<p>I wanted to test <em>actual Kubernetes deployment</em>, so I used <strong>kind</strong> (Kubernetes in Docker):</p>
<pre><code class="language-bash">kind create cluster --name dev
kubectl get nodes
</code></pre>
<p>If the node shows <code>Ready</code>, the cluster is healthy.</p>
<h2>Step 4 — Deploy the blog into the cluster</h2>
<p>First I built the production image locally:</p>
<pre><code class="language-bash">docker build --target prod -t blog-prod:local .
</code></pre>
<p>Then I loaded it into kind:</p>
<pre><code class="language-bash">kind load docker-image blog-prod:local --name dev
</code></pre>
<p>Then I applied a Kubernetes manifest (Deployment + Service).</p>
<p>Finally, I used port‑forward to access it locally:</p>
<pre><code class="language-bash">kubectl port-forward svc/blog 8081:80
</code></pre>
<p>Now the blog was running <strong>inside Kubernetes</strong>, accessible at <code>http://localhost:8081</code>.</p>
<h2>Common issues I hit (and how I fixed them)</h2>
<h3>1) Docker daemon not running</h3>
<p>Error:</p>
<pre><code>Cannot connect to the Docker daemon at ... docker.sock
</code></pre>
<p>Fix: Make sure Docker Desktop is <em>actually running</em>, then retry.</p>
<h3>2) Port already in use</h3>
<p>Error:</p>
<pre><code>bind: address already in use
</code></pre>
<p>Fix: change the port in <code>kubectl port-forward</code>, e.g. <code>8081:80</code>.</p>
<h3>3) Compose not found</h3>
<p>If <code>docker compose</code> isn’t available, Docker Desktop isn’t fully initialized. Starting Docker Desktop fixes it.</p>
<h2>The pipeline problem I noticed</h2>
<p>This flow is powerful, but the pipeline still has a weakness:</p>
<p><strong>Every push builds everything</strong>, even when only a small change happened. That wastes time in CI and makes deployments slower than they need to be.</p>
<p>Examples:</p>
<ul>
<li>Editing a single Markdown post should not trigger full tests</li>
<li>Updating Kubernetes YAML should not rebuild the entire site</li>
<li>Changing <code>src/</code> should trigger tests, but a typo fix in content shouldn’t</li>
</ul>
<h2>My idea: a “deploy‑impact” analyzer tool</h2>
<p>I want a tiny tool that <strong>analyzes the changed files</strong> and produces metadata for CI so it can decide what to do.</p>
<p>Example output:</p>
<pre><code class="language-json">{
"changedAreas": ["content"],
"shouldBuild": true,
"shouldTest": false,
"reason": "Only markdown content changed"
}
</code></pre>
<p>This lets CI be smarter:</p>
<ul>
<li>Content change → build only</li>
<li>UI or config change → build + test</li>
<li>Infrastructure change → deploy only</li>
</ul>
<p>This is the next tool I want to build and integrate.</p>
<h2>My final thoughts</h2>
<p>Now I can:</p>
<ul>
<li>Build my Gatsby site in Docker</li>
<li>Serve production output locally</li>
<li>Deploy to a Kubernetes cluster for realistic testing</li>
</ul>
<p>The last step is to make CI smarter and faster. The deploy‑impact tool is my solution to cut wasted work and speed up deploys.</p>
<p>If you’re trying something similar, I highly recommend this approach. It makes local testing feel like real production.</p>]]></content:encoded>
</item>
<item>
<title><![CDATA[Containerizing Gatsby: A CI-Friendly DevOps Path]]></title>
<link>http://irenaapp.de//blog-containerizing-gatsby-ci/</link>
<guid>http://irenaapp.de//blog-containerizing-gatsby-ci/</guid>
<pubDate>Thu, 05 Feb 2026 10:00:00 GMT</pubDate>
<description><![CDATA[Why containerize a Gatsby blog? A Gatsby site is fast and portable, but the workflow around it can drift between machines. Containerizing…]]></description>
<content:encoded><![CDATA[<h2>Why containerize a Gatsby blog?</h2>
<p>A Gatsby site is fast and portable, but the workflow around it can drift between machines. Containerizing the app makes the build reproducible, keeps dependencies consistent, and gives you a production image that behaves like your real deployment environment.</p>
<h2>The core idea</h2>
<p>We want one Docker image for development and one for production:</p>
<ul>
<li><strong>Dev image</strong> runs <code>gatsby develop</code> for hot reload</li>
<li><strong>Prod image</strong> runs <code>gatsby build</code> and serves static assets with nginx</li>
</ul>
<p>This makes CI simple: build the production image, run tests, and deploy only when necessary.</p>
<h2>What CI should decide</h2>
<p>Not every change needs a full build or test run. A small metadata script can scan changed files and decide what to do:</p>
<ul>
<li>Content changes (<code>content/</code>, <code>.md</code>) -> build only</li>
<li>UI or config changes (<code>src/</code>, <code>gatsby-*.js</code>, <code>package.json</code>) -> build + test</li>
<li>Infra changes (<code>k8s/</code>, <code>netlify/</code>) -> deploy pipeline only</li>
</ul>
<p>This lets your pipeline skip work without skipping safety.</p>
<h2>Example CI flow</h2>
<ol>
<li><strong>Analyze changes</strong> and output impact metadata</li>
<li><strong>Build</strong> the production image when needed</li>
<li><strong>Run tests</strong> for UI or config changes</li>
<li><strong>Deploy</strong> only when the image and tests pass</li>
</ol>
<h2>Why this is DevOps-friendly</h2>
<p>You get the best of both worlds:</p>
<ul>
<li>Developers iterate fast with a consistent dev container</li>
<li>CI builds match production behavior</li>
<li>Kubernetes deploys a predictable, static image</li>
</ul>
<h2>Takeaway</h2>
<p>Containerization turns Gatsby into a clean, repeatable unit. With a small impact-analysis step, CI becomes smarter and faster without sacrificing reliability.</p>]]></content:encoded>
</item>
<item>
<title><![CDATA[React without the Magic Mysticism]]></title>
<link>http://irenaapp.de//blog-react/</link>
<guid>http://irenaapp.de//blog-react/</guid>
<pubDate>Tue, 27 Jan 2026 14:33:00 GMT</pubDate>
<description><![CDATA[React without the Magic Mysticism React has a weird reputation. Some people treat it like magic.
Others treat it like a nightmare.
Most…]]></description>
<content:encoded><![CDATA[<h1>React without the Magic Mysticism</h1>
<p>React has a weird reputation.</p>
<p>Some people treat it like magic.
Others treat it like a nightmare.
Most tutorials explain <em>how</em> to use it, but not <em>why</em> it feels the way it does.</p>
<p>Let’s fix that.</p>
<p>No hype. No “React is easy bro”. Just reality.</p>
<h2>React Is Not a Framework — It’s a Mental Model</h2>
<p>React doesn’t tell you how to build everything.</p>
<p>It gives you <strong>one powerful idea</strong>:</p>
<blockquote>
<p>Your UI is a function of state.</p>
</blockquote>
<p>Change the state → React updates the UI.
That’s it. That’s the core.</p>
<p>Once this clicks, React stops feeling confusing.</p>
<h2>Components: Not Reusable HTML, Reusable Thinking</h2>
<p>Components aren’t just chunks of UI.</p>
<p>They are:</p>
<ul>
<li>Decisions</li>
<li>Boundaries</li>
<li>Responsibilities</li>
</ul>
<p>A good component:</p>
<ul>
<li>Does <strong>one thing</strong></li>
<li>Has <strong>clear inputs (props)</strong></li>
<li>Owns <strong>minimal state</strong></li>
</ul>
<p>If your component feels hard to reason about, it’s probably doing too much.</p>
<h2>State Is Where Bugs Are Born</h2>
<p>Most React bugs are not React bugs.</p>
<p>They’re <strong>state problems</strong>.</p>
<ul>
<li>State stored too high</li>
<li>State duplicated</li>
<li>State mutated instead of replaced</li>
</ul>
<p>Rule of thumb:</p>
<blockquote>
<p>If you’re confused about your UI, trace the state — not the JSX.</p>
</blockquote>
<h2>Effects Are Not Lifecycle Hooks (Stop Using Them Like That)</h2>
<p><code>useEffect</code> is powerful — and abused.</p>
<p>It’s not:</p>
<ul>
<li><code>componentDidMount</code></li>
<li><code>componentDidUpdate</code></li>
<li>A place to “just put code”</li>
</ul>
<p>It’s for <strong>syncing React with the outside world</strong>:</p>
<ul>
<li>APIs</li>
<li>Subscriptions</li>
<li>Timers</li>
<li>Browser APIs</li>
</ul>
<p>If you don’t need to sync, you probably don’t need an effect.</p>
<h2>React Rewards Simplicity (Even When You Resist It)</h2>
<p>React feels hard when you:</p>
<ul>
<li>Over-abstract too early</li>
<li>Add libraries for tiny problems</li>
<li>Fight the data flow</li>
</ul>
<p>React feels good when you:</p>
<ul>
<li>Keep state local</li>
<li>Pass props clearly</li>
<li>Let components stay dumb</li>
</ul>
<p>Simple code ages better. Always.</p>
<h2>Final Thought</h2>
<p>React isn’t about being clever. It’s about being <strong>predictable</strong>.</p>
<ul>
<li>Predictable state.</li>
<li>Predictable data flow.</li>
<li>Predictable UI.</li>
</ul>
<p>Once you stop fighting that, React stops fighting you.</p>
<p>🚀 Happy Coding!</p>]]></content:encoded>
</item>
<item>
<title><![CDATA[Understanding React’s Data Flow]]></title>
<link>http://irenaapp.de//blog-react-hooks-and-context/</link>
<guid>http://irenaapp.de//blog-react-hooks-and-context/</guid>
<pubDate>Fri, 23 Jan 2026 14:37:00 GMT</pubDate>
<description><![CDATA[Understanding React’s Data Flow: A Mental Model That Scales How props, hooks, and context actually work together ReasonReact Hook Recipes…]]></description>
<content:encoded><![CDATA[<h2>Understanding React’s Data Flow: A Mental Model That Scales How props, hooks, and context actually work together</h2>
<h2>ReasonReact Hook Recipes: Props, Data Flow, and Context Explained</h2>
<p>React hooks are powerful—but they only really click once you understand <strong>how data flows through components</strong>.</p>
<p>When ReasonReact 0.7.0 introduced hooks, the APIs looked familiar, but the <em>mental model</em> felt different. It took some digging—reading docs, source code, and experimenting—to understand how hooks, props, and context actually fit together in ReasonReact.</p>
<p>This article puts everything in one place.</p>
<h2>Why Props Still Matter in a Hooks World</h2>
<p>Hooks didn’t replace props.
They <strong>amplified</strong> them.</p>
<p>Props are still the primary way data moves <strong>down</strong> the component tree. Hooks simply give components new ways to <em>react</em> to that data.</p>
<p>If you misunderstand props, hooks will feel magical and confusing.
If you understand props, hooks feel predictable and powerful.</p>
<h2>Understanding <code>@react.component</code></h2>
<p>One key to ReasonReact is understanding what <code>@react.component</code> actually does.</p>
<p>At a high level, it:</p>
<ul>
<li>Turns a function into a React component</li>
<li>Treats function arguments as <strong>props</strong></li>
<li>Re-renders the component when props or state change</li>
</ul>
<p>This means:</p>
<ul>
<li>Props are immutable</li>
<li>Components are pure functions of props + state</li>
<li>Data always flows <strong>top-down</strong></li>
</ul>
<p>Once this clicks, hooks make much more sense.</p>
<h2>React Context and <code>useContext</code></h2>
<p>Context was the least obvious hook for me at first—but once you see how it fits into the props model, it becomes intuitive.</p>
<p>Context is <strong>not global state</strong>.
It’s a way to <strong>inject props deeper</strong> into the component tree without prop drilling.</p>
<h3>Mental Model</h3>
<p>Think of Context as:</p>
<blockquote>
<p>“Invisible props that React wires for you.”</p>
</blockquote>
<p>A Provider sets the value.
Consumers read the value using <code>useContext</code>.</p>
<h3>When to Use Context</h3>
<p>Use context for:</p>
<ul>
<li>Themes</li>
<li>Auth state</li>
<li>Locale / language</li>
<li>Feature flags</li>
</ul>
<p>Avoid using it for:</p>
<ul>
<li>Frequently changing UI state</li>
<li>Large, complex data trees</li>
</ul>
<h2>Hook Recipes That Actually Work</h2>
<p>Here are some practical patterns that scale well in real apps.</p>
<h3>1. Local State with <code>useState</code></h3>
<p>Use <code>useState</code> for:</p>
<ul>
<li>UI toggles</li>
<li>Form state</li>
<li>Temporary component state</li>
</ul>
<p>Keep it <strong>close to where it’s used</strong>.</p>
<h3>2. Derived State with Pure Functions</h3>
<p>If state can be derived from props:</p>
<ul>
<li>Don’t store it</li>
<li>Compute it</li>
</ul>
<p>This keeps components predictable and avoids sync bugs.</p>
<h3>3. Context for Cross-Cutting Concerns</h3>
<p>Create small, focused contexts:</p>
<ul>
<li><code>ThemeContext</code></li>
<li><code>AuthContext</code></li>
<li><code>SettingsContext</code></li>
</ul>
<p>Smaller contexts = fewer re-renders.</p>
<h3>4. Hooks as Logic Containers</h3>
<p>Custom hooks shine when they:</p>
<ul>
<li>Encapsulate side effects</li>
<li>Hide implementation details</li>
<li>Return simple, declarative values</li>
</ul>
<p>Hooks should feel like <strong>APIs</strong>, not utilities.</p>
<h2>Data Flow Rules That Never Change</h2>
<p>No matter how many hooks you use, these rules stay true:</p>
<ul>
<li>Props flow <strong>down</strong></li>
<li>Events flow <strong>up</strong></li>
<li>State lives where it’s owned</li>
<li>Context replaces plumbing, not architecture</li>
</ul>
<p>Once you internalize this, React stops feeling “magical” and starts feeling <strong>mechanical—in a good way</strong>.</p>
<h2>Final Thoughts</h2>
<p>Hooks didn’t change React’s core philosophy.
They just gave us better tools to express it.</p>
<p>Understanding props, data flow, and context at a mental-model level is what separates <em>React users</em> from <em>React architects</em>.</p>
<p>If you get this right, everything else becomes easier.</p>]]></content:encoded>
</item>
<item>
<title><![CDATA[React Props & Data Flow the Way It Works]]></title>
<link>http://irenaapp.de//blog-react-props-deep-dive/</link>
<guid>http://irenaapp.de//blog-react-props-deep-dive/</guid>
<pubDate>Fri, 23 Jan 2026 14:37:00 GMT</pubDate>
<description><![CDATA[React props look simple — until your app grows. At first, props feel like HTML attributes.
Then suddenly you're passing data through five…]]></description>
<content:encoded><![CDATA[<p>React props look simple — until your app grows. At first, props feel like HTML attributes.
Then suddenly you're passing data through five components and debugging where it disappeared.</p>
<p>This article explains <strong>how props actually work</strong>, why React enforces them, and how to use them without losing your sanity.</p>
<p>React props form the backbone of React's unidirectional data flow—a deliberate design where data travels strictly down from parent components to children, while changes bubble up through callbacks. When React renders <Parent><Child data={value} /></Parent>, the Child component receives { data: value } as its first function argument—plain JavaScript objects with no special powers or hidden magic. Parents own the source of truth and pass immutable snapshots down the tree; children read-only display or forward those snapshots. This creates a clear ownership model: data lives in one place, flows predictably, and updates follow a single path.</p>
<p>This pattern eliminates the chaos of two-way binding systems where any component can mutate shared state. Instead of "who changed my data?", you trace a straight line: parent updates state → React re-renders → new props cascade down. Child components stay pure—they render the same input props identically every time, making them testable, reusable, and debuggable. When interaction happens (button click, form submit), children don't mutate props directly; they call callback functions passed as props, delegating the actual state change back to the responsible parent. This separation of concerns scales beautifully from button components to entire applications.</p>
<p>The real power emerges as apps grow: props become explicit contracts between components. A Header needing user data gets { user, onLogout } from its parent; a Form gets { initialData, onSubmit }. Developers instantly see data dependencies without hunting through files. When prop drilling becomes painful (passing the same theme through five irrelevant components), useContext steps in naturally. Mastering this flow—data down, actions up—transforms React from "magical HTML" into a logical state machine where every render has a single predictable cause.</p>
<h2>Props Are Just Function Arguments</h2>
<p>React components are functions. Props are arguments.</p>
<pre><code class="language-js">function Greeting(props) {
return <h1>Hello {props.name}</h1>;
}
</code></pre>
<p>When you write <code>Greeting name="Irene"</code> React calls:</p>
<pre><code class="language-js">Greeting({ name: 'Irene' });
Props = plain JavaScript objects. No magic, no mysticism.
</code></pre>
<h2>Data Flows Down Only</h2>
<p>Props flow one direction — parent → child.</p>
<pre><code class="language-jsx">const movies = [
{ id: 1, title: 'Inception', rating: 8.8, poster: 'inception.jpg' },
{ id: 2, title: 'Interstellar', rating: 8.6, poster: 'interstellar.jpg' },
];
function MovieLibrary() {
return (
<div className="library">
{movies.map(movie => (
<MovieCard
key={movie.id}
title={movie.title}
rating={movie.rating}
poster={movie.poster}
/>
))}
</div>
);
}
</code></pre>
<p>Parent owns the movie data. Cards just display it.</p>
<p>Destructuring for Readability</p>
<pre><code class="language-jsx">function MovieCard({
title,
rating,
poster,
genre = 'Drama',
onWatchlist = false
}) {
return (
<div className={`movie-card ${onWatchlist ? 'watchlist' : ''}`}>
<img src={poster} alt={title} loading="lazy" />
<h3>{title}</h3>
<p>⭐ {rating} - {genre}</p>
{onWatchlist && <span className="badge">📌 Watchlist</span>}
</div>
);
}
</code></pre>
<h2>Functions as Props Real App Power</h2>
<p>Interactive Movie Library with Watchlist:</p>
<pre><code class="language-jsx">function MovieGrid({ movies, onToggleWatchlist, onRate }) {
return (
<div className="movie-grid">
{movies.map(movie => (
<MovieCard
key={movie.id}
title={movie.title}
rating={movie.rating}
poster={movie.poster}
onWatchlist={movie.onWatchlist}
onToggle={() => onToggleWatchlist(movie.id)}
onRate={(newRating) => onRate(movie.id, newRating)}
/>
))}
</div>
);
}
function MovieLibrary() {
const [movies, setMovies] = React.useState([
{ id: 1, title: 'Inception', rating: 8.8, poster: 'inception.jpg', onWatchlist: false },
{ id: 2, title: 'Interstellar', rating: 8.6, poster: 'interstellar.jpg', onWatchlist: true },
]);
const toggleWatchlist = (movieId) => {
setMovies(movies.map(movie =>
movie.id === movieId
? { ...movie, onWatchlist: !movie.onWatchlist }
: movie
));
};
const updateRating = (movieId, newRating) => {
setMovies(movies.map(movie =>
movie.id === movieId
? { ...movie, rating: newRating }
: movie
));
};
return (
<div className="library">
<h1>My Movie Library</h1>
<MovieGrid
movies={movies}
onToggleWatchlist={toggleWatchlist}
onRate={updateRating}
/>
</div>
);
}
</code></pre>
<h2>The Prop Drilling Trap</h2>
<p>Before Context (messy):</p>
<pre><code class="language-jsx">function App() {
const [theme, setTheme] = React.useState('dark');
return <Header theme={theme} setTheme={setTheme} />;
}
function Header({ theme, setTheme }) {
return <MovieGrid theme={theme} setTheme={setTheme} />; // Doesn't need theme
}
</code></pre>
<p>After Context clean:</p>
<pre><code class="language-jsx">const ThemeContext = React.createContext();
function App() {
const [theme, setTheme] = React.useState('dark');
return (
<ThemeContext.Provider value={{ theme, setTheme }}>
<Header />
</ThemeContext.Provider>
);
}
function MovieCard() {
const { theme } = React.useContext(ThemeContext);
return <div className={`movie-card ${theme}`}>...</div>;
}
</code></pre>
<h2>Solution: React Context</h2>
<pre><code class="language-jsx">const ThemeContext = React.createContext();
const UserContext = React.createContext();
function App() {
const theme = 'dark';
const user = { name: 'Sofia' };
return (
<ThemeContext.Provider value={theme}>
<UserContext.Provider value={user}>
<Header />
</UserContext.Provider>
</ThemeContext.Provider>
);
}
function Menu() {
const theme = React.useContext(ThemeContext);
const user = React.useContext(UserContext);
return (
<div className={`menu ${theme}`}>
Welcome {user.name}
</div>
);
}
</code></pre>
<h2>Props Are Immutable</h2>
<pre><code class="language-jsx">// ❌ NEVER do this
function BadMovieCard({ movies }) {
movies.onWatchlist = true; // Direct mutation!
return <div>...</div>;
}
// Always create new data
function GoodMovieCard({ movies }) {
const moviesWithStatus = movies.map(movie => ({
...movie,
displayRating: movie.rating > 8 ? '🔥' + movie.rating : movie.rating
}));
return <div>...</div>;
}
</code></pre>
<h2>Type Safety That Actually Saves You</h2>
<p>TypeScript the modern way</p>
<pre><code class="language-jsx">interface UserCardProps {
user: {
id: number;
name: string;
avatar: string;
isOnline: boolean;
};
onFollow: () => void;
onMessage: (userId: number) => void;
showStats?: boolean;
}
function UserCard({
user,
onFollow,
onMessage,
showStats = false
}: UserCardProps) {
return (
<div className="user-card">
<div className={`status ${user.isOnline ? 'online' : 'offline'}`} />
<img src={user.avatar} alt={user.name} />
<span>{user.name}</span>
{showStats && <span>Posts: 42</span>}
<div className="actions">
<button onClick={onFollow}>Follow</button>
<button onClick={() => onMessage(user.id)}>Message</button>
</div>
</div>
);
}
</code></pre>
<h2>PropTypes for JavaScript projects:</h2>
<pre><code class="language-jsx">import PropTypes from 'prop-types';
UserCard.propTypes = {
user: PropTypes.shape({
id: PropTypes.number.isRequired,
name: PropTypes.string.isRequired,
avatar: PropTypes.string,
isOnline: PropTypes.bool
}).isRequired,
onFollow: PropTypes.func.isRequired,
onMessage: PropTypes.func.isRequired,
showStats: PropTypes.bool
};
UserCard.defaultProps = {
showStats: false
};
</code></pre>
<h2>TypeScript MovieCard, Production Ready</h2>
<pre><code class="language-jsx">interface Movie {
id: number;
title: string;
rating: number;
poster: string;
onWatchlist?: boolean;
}
interface MovieCardProps {
movie: Movie;
onToggleWatchlist: (id: number) => void;
onRate: (id: number, rating: number) => void;
}
function MovieCard({
movie,
onToggleWatchlist,
onRate
}: MovieCardProps) {
return (
<div className={`movie-card ${movie.onWatchlist ? 'watchlist' : ''}`}>
<img src={movie.poster} alt={movie.title} />
<h3>{movie.title}</h3>
<p>⭐ {movie.rating}</p>
<button onClick={() => onToggleWatchlist(movie.id)}>
{movie.onWatchlist ? 'Remove' : 'Add to Watchlist'}
</button>
<input
type="range"
min="0"
max="10"
value={movie.rating}
onChange={(e) => onRate(movie.id, Number(e.target.value))}
/>
</div>
);
}
</code></pre>
<pre><code class="language-js">
MovieLibrary (owns data) ──props──> MovieGrid ──props──> MovieCard
↑ │
│────────state changes──────────────│
</code></pre>
<pre><code class="language-jsx">// Top level: owns the data
function MovieLibrary() {
const [movies, setMovies] = React.useState([
{ id: 1, title: 'Inception', rating: 8.8, watchlist: false },
{ id: 2, title: 'Interstellar', rating: 8.6, watchlist: true },
]);
const toggleWatchlist = (id) => {
setMovies(prev =>
prev.map(movie =>
movie.id === id
? { ...movie, watchlist: !movie.watchlist }
: movie
)
);
};
const updateRating = (id, rating) => {
setMovies(prev =>
prev.map(movie =>
movie.id === id
? { ...movie, rating }
: movie
)
);
};
return (
<MovieGrid
movies={movies}
onToggleWatchlist={toggleWatchlist}
onUpdateRating={updateRating}
/>
);
}
// Middle: just forwards data/behaviour
function MovieGrid({ movies, onToggleWatchlist, onUpdateRating }) {
return (
<div className="movie-grid">
{movies.map(movie => (
<MovieCard
key={movie.id}
movie={movie}
onToggleWatchlist={() => onToggleWatchlist(movie.id)}
onUpdateRating={(rating) => onUpdateRating(movie.id, rating)}
/>
))}
</div>
);
}
// Leaf: pure presentation + callbacks
function MovieCard({ movie, onToggleWatchlist, onUpdateRating }) {
return (
<article className="movie-card">
<h3>{movie.title}</h3>
<p>⭐ {movie.rating}</p>
<button onClick={onToggleWatchlist}>
{movie.watchlist ? 'Remove from watchlist' : 'Add to watchlist'}
</button>
<input
type="range"
min="0"
max="10"
value={movie.rating}
onChange={(e) => onUpdateRating(Number(e.target.value))}
/>
</article>
);
}
</code></pre>
<p>Props = explicit data contracts between components.</p>
<p>Parent owns the data</p>
<p>Parent passes data/behavior via props</p>
<p>Child uses props immutably</p>
<p>Child notifies parent via callbacks</p>
<p>Parent updates state → triggers re-render</p>
<h2>To sum-up: The Props Mental Model</h2>
<p>Mastering React props means seeing your app as a predictable data pipeline: MovieLibrary → MovieGrid → MovieCard.
When a user adds Inception to their watchlist, MovieCard calls its callback → MovieGrid forwards the call → MovieLibrary updates state → React re-renders everything with fresh props. No component wonders "where did this data come from?" No mutation bugs. No circular dependencies.</p>
<p>This pattern scales from 5-line components to 50k-line apps. Prop drilling? Solve with useContext. Global state? Add Zustand. But props remain the foundation—explicit, immutable contracts that make React logical, not magical.</p>
<p>Next time you debug: Ask "who owns this data?" Follow the props down from that owner. You've found your answer.</p>
<p>Happy coding!</p>]]></content:encoded>
</item>
<item>
<title><![CDATA[ React’s Data Flow]]></title>
<link>http://irenaapp.de//blog-react-hooks-and-context-practice/</link>
<guid>http://irenaapp.de//blog-react-hooks-and-context-practice/</guid>
<pubDate>Fri, 23 Jan 2026 14:37:00 GMT</pubDate>
<description><![CDATA[React Data Flow How props, hooks, and context actually work together 🍕 Think of Pizza React Data Flow Explained with Pizza 🍕 Think of a…]]></description>
<content:encoded><![CDATA[<h1>React Data Flow</h1>
<h2>How props, hooks, and context actually work together 🍕</h2>
<h2>Think of Pizza React Data Flow Explained with Pizza 🍕</h2>
<p>Think of a React app like a pizza kitchen.</p>
<ul>
<li>The <strong>parent component</strong> owns the pizza</li>
<li><strong>Props</strong> deliver the pizza to children</li>
<li><strong>Children never change the pizza directly</strong></li>
<li>They can only <strong>ask</strong> for changes</li>
</ul>
<p>That’s React data flow in one sentence.</p>
<h2>🍕 The Parent Owns the Pizza (State)</h2>
<pre><code class="language-jsx">function PizzaShop() {
const [pizza, setPizza] = React.useState("Margherita");
function changePizza(newPizza) {
setPizza(newPizza);
}
return (
<div>
<h1>Today's Pizza: {pizza}</h1>
<PizzaMenu
pizza={pizza}
onChangePizza={changePizza}
/>
</div>
);
}
</code></pre>
<p>Mental model:</p>
<p>PizzaShop owns the state</p>
<p>It decides what pizza exists</p>
<p>Data flows down via props</p>
<p>🧑🍳 Child Receives Pizza via Props</p>
<pre><code class="language-js">
function PizzaMenu({ pizza, onChangePizza }) {
return (
<div>
<p>Current choice: {pizza}</p>
<button onClick={() => onChangePizza("Pepperoni")}>
Switch to Pepperoni
</button>
</div>
);
}
</code></pre>
<h2>What to remenber:</h2>
<p>❌ Children do not mutate props</p>
<p>✅ Children request changes using callbacks</p>
<h2>🔄 One-Way Data Flow The Rule</h2>
<p>React always follows this direction:</p>
<pre><code class="language-js">
State (PizzaShop)
↓
Props (PizzaMenu)
↓
User Event
↑
State Update
</code></pre>
<p>Breaking this rule is how bugs are born.</p>
<h2>🍕 What About Context?</h2>
<p>Context is pizza delivery without passing boxes through every room.</p>
<pre><code class="language-js">const PizzaContext = React.createContext();
function PizzaProvider({ children }) {
const [pizza, setPizza] = React.useState("Margherita");
return (
<PizzaContext.Provider value={{ pizza, setPizza }}>
{children}
</PizzaContext.Provider>
);
}
</code></pre>
<pre><code class="language-jsx">function PizzaConsumer() {
const { pizza, setPizza } = React.useContext(PizzaContext);
return (
<button onClick={() => setPizza("Hawaiian")}>
Change to Hawaiian
</button>
);
}
</code></pre>
<h2>Important to remeber:</h2>
<p>Context does not change data flow. It only removes prop drilling</p>
<p>🍕 State owns the pizza</p>
<p>📦 Props deliver the pizza</p>
<p>🔄 Events request changes</p>
<p>🧠 Context skips plumbing, not rules</p>
<p>Once this clicks, React stops feeling magical and starts feeling predictable.</p>]]></content:encoded>
</item>
<item>
<title><![CDATA[Props Mental Model: React vs Vue Data flow]]></title>
<link>http://irenaapp.de//blog-react-props-vue/</link>
<guid>http://irenaapp.de//blog-react-props-vue/</guid>
<pubDate>Tue, 20 Jan 2026 14:37:00 GMT</pubDate>
<description><![CDATA[Props Mental Model: React vs Vue As a React developer, I wanted to dive into Vue to learn how it approached building JavaScript UI. How do…]]></description>
<content:encoded><![CDATA[<h2>Props Mental Model: React vs Vue</h2>
<p>As a React developer, I wanted to dive into Vue to learn how it approached building JavaScript UI. How do they differ? Is one better?
Let's start by looking at their taglines. React is "a declarative, efficient, and flexible JavaScript library for building user interfaces." Vue is "a progressive, incrementally-adoptable JavaScript framework for building UI on the web</p>
<h2>Highlights</h2>
<p>At a high level, the frameworks take similar approaches to the same goal.
React is JavaScript-centric vs Vue uses hybrid HTML template/JS.
React uses a push update model vs Vue implements reactivity via observing.
Vue has more built-in. React is more barebones and relies on community.</p>
<pre><code class="language-jsx">App ──props──> Profile ──props──> Greeting
↑ callbacks │
(setUser, onLogout) (read-only display)
</code></pre>
<p>React props are plain JavaScript objects passed as function arguments. Components are pure functions: Greeting({ name, role }). Data flows strictly down via props. Actions flow up via callback props like onClick, onChange. Parent owns state, children are read-only—no mutations allowed. Re-renders happen when parent state changes, cascading fresh props down. Explicit control, predictable, scales with discipline</p>
<p>Vue: Reactive, Template-Driven (HTML-First)</p>
<pre><code class="language-js">
App ──props──> Profile ──props──> Greeting
↑ emits │ emits
($emit('update:user')) (read-only)
</code></pre>
<p>Vue props work similarly—data down via <Greeting :name="user.name" /> (note kebab-case in templates). But Vue's reactive system auto-tracks dependencies. Child communicates via $emit('custom-event'), parent listens with @custom-event="handler". Props are still immutable, but Vue's reactivity makes updates feel automatic—change user.name and {{ name }} updates everywhere it's used. Magical DX, less boilerplate</p>
<p>React forces you to think in explicit state updates. Vue hides reactivity complexity behind templates. Both enforce data down, events up—just different flavors</p>
<h2>Language approach</h2>
<p>Let's jump right in and look at a pretty full-featured component. I'm going ahead with the Vue 3 composition API because it seems like the direction Vue is heading. There are obvious parallels: the Vue component options API is to React class components as Vue 3 composition API is to React hooks.</p>
<pre><code class="language-jsx">// UserProfile.vue
<div>
<div>{{ id }}</div>
<Avatar v-if="showAvatar" :id="id" />
<UserBody v-if="user" :user="user" />
<button @click="$emit('follow-click')">Follow</button>
</div>
defineComponent({
props: {
id: { type: String },
showAvatar: { type: Boolean },
},
setup(props) {
const {id} = toRefs(props);
const user = ref(undefined);
function updateUser() {
fetchUser(id.value).then(data => {
user.value = data;
});
}
onMounted(updateUser);
watch(id, updateUser);
return {user};
}
})
</code></pre>
<p>React</p>
<pre><code class="language-jsx">
// React
function UserProfile({id, showAvatar, onFollowClick}: {
id: string,
showAvatar: boolean,
onFollowClick: () => void,
}) {
const [user, setUser] = React.useState(undefined);
React.useEffect(() => {
fetchUser(id).then(setUser);
}, [id]);
return (
<div>
<div>{id}</div>
{showAvatar ? <Avatar id={id} /> : null}
{user !== undefined ? <UserBody user={user} /> : null}
<button onClick={onFollowClick}>Follow</button>
</div>
);
}
</code></pre>
<h2>React's JSX is just sugar for JavaScript.</h2>
<p>In a way, you could also say that Vue's templates are also JavaScript sugar. However, the transform is more involved and Vue-specific.
Pros and Cons
One advantage of Vue's template syntax is that because it is more restrictive, the compiler is able to perform more optimizations, such as separating out static template content to avoid rerenders. React can do something similar with a Babel plugin but this is not common. Theoretically, I believe Vue could make more optimizations from template syntax.</p>
<p>A disadvantage with Vue templates is that there are times when JavaScript's expressiveness is sorely missed or even necessary. In those cases, Vue recommends using a render function, either via the more verbose createElement or JSX. An example I ran into is wanting a local variable inside a template loop. Translating between Vue template and JSX is a manual process. I think you probably need to be familiar with both template and JSX to be a Vue developer, in which case React's one approach seems better.
If you use React hooks, React components are just functions. All the logic lives inside this function. Vue separates the component definition from the template (or render function). Using the new Composition API above, the component definition is inside one setup function. This is a notable difference; React hooks are run on every render but setup is only run once on initialization. Vue sets up listeners (lifecycle and reactive values) whereas React specifies effects on each render.</p>
<h2>Event Handling</h2>
<p>Event handling is another example of the differing language approach. React has no special syntax; it's just JavaScript functions. Vue provides syntax for listening to and emitting events.</p>
<pre><code class="language-js">// MyVueComponent
<button @click="$emit('increment')">Increment</button>
<MyVueComponent @increment="methodName" />
// MyReactComponent
<button onClick={props.onIncrement}>Increment</button>
<MyReactComponent onIncrement={jsFunction} />
</code></pre>
<p>You can see here the differing approaches to events. React passes a JavaScript function to the component. Vue components emit events, which are identified as strings with associated data.
Static analysis</p>
<p>At a high level, React is better suited for static analysis, such as TypeScript. Its JavaScript-centric approach puts it closer to the language so most editor/tooling just works. I set up VSCode with Vetur (Vue's recommended tooling) and didn't get semantic langauge features (e.g. checking, autocomplete, go to definition) inside the Vue template. Note: I realised Vetur has an experimental setting for Template Interpolation Service which adds a lot of these features but it still misses features like find references.</p>
<p>Some Vue features like named slots, events, and their props as React children equivalent are too dynamic for full static analysis. For example, components can emit custom events but there isn't an obvious way to write out that contract.</p>
<p>Vue provides a global namespace although it is not always recommended. For example, you can register components by name to the global namespace. Vue plugins can inject global methods, properties, and mixins. Global namespaces, while convenient at times, play less nicely with tooling and scalable codebases.</p>
<h2>Update model</h2>
<p>The biggest functional difference between Vue and React is how they handle updates. Vue uses observables (via JavaScript Proxies or defineProperty) to implement reactivity. In short, it modifies data to track when properties are read or written. This allows for fine-grained dependency tracking; Vue knows which properties have been read so it can rerender and update views only when those properties change. This is smarter than a stock React.memo, which compares equality for all props.
In comparison, React uses a push update model. Rerenders are triggered by a function call somewhere (state update or reducer dispatch). When a React component updates, it will rerender all its children as well.</p>
<pre><code class="language-js">
// MyVueComponent
<button @click="count += 1">{{ count }}</button>
Vue.extend({
data: {
count: 0
}
})
function MyReactComponent() {
const [count, setCount] = React.useState(0);
return <button onClick={() => setCount(count => count + 1)}>{count}</button>;
}
</code></pre>
<p>The way I think of Vue's update model is as if all components were wrapped in React.memo and the equality function was a dynamic one that compared only props/state that were used on the last render.</p>
<p>Vue's reactivity model operates like <strong>React components universally wrapped in <code>React.memo()</code></strong> with dynamically generated equality functions—it automatically tracks exactly which props and reactive state (<code>data</code>, <code>ref</code>, <code>reactive</code>) were accessed during the last render, then only re-renders when <em>those specific dependencies</em> change.</p>
<p>Unlike React's static dependency arrays in <code>useEffect</code>/<code>useMemo</code>, Vue uses <strong>Proxy-based reactivity</strong> (ES6 Proxies intercept property access/set operations) to build a dependency graph at runtime: when your template accesses <code>{{ user.name }}</code>, Vue records that <code>user.name</code> is a dependency; when <code>user.name</code> changes later, only components using that exact property re-render.</p>
<p>This granular tracking happens <strong>out-of-the-box</strong> without manual optimization, making Vue's default performance superior for complex UIs. It's strikingly similar to <a href="https://mobx.js.org/">MobX</a> where reactive "atoms" (individual properties) trigger derived "computed" values, but Vue extends this to templates:</p>
<pre><code class="language-js">computed: {
displayName() {
return this.user.name.toUpperCase();
}
}
</code></pre>
<p>automatically reruns only when user.name changes—React would need useMemo with a stable user reference or a wrapper component.</p>
<pre><code class="language-js">undefined
</code></pre>
<p>However, Vue's model isn't perfect. <strong>Computed properties currently re-run their getter whenever underlying data changes</strong>, even if the output stays identical (<code>user.name = user.name</code> still triggers), lacking React's <code>useMemo</code> strictness.</p>
<p>Vue's reactivity also has <strong>destructuring gotchas</strong>—pulling <code>{ count } = store</code> into local variables breaks reactivity since Proxies only track direct property access. Composition API <code>ref()</code> requires explicit <code>.value</code> access or <code>toRefs()</code> wrappers, while <code>reactive()</code> objects must be consumed directly.</p>
<p>React's explicitness forces discipline (<code>React.memo</code>, <code>useCallback</code>) but makes performance predictable; Vue <strong>hides complexity</strong> behind "automatic" reactivity, trading boilerplate for potential stale closure bugs.</p>
<p>Both achieve <strong>data down/actions up</strong>, but Vue prioritizes DX while React prioritizes explicit control (<a href="https://v3.vuejs.org/guide/reactivity-fundamentals.html#destructuring-reactive-state">Vue reactivity fundamentals</a>, <a href="https://v3.vuejs.org/guide/composition-api-introduction.html#reactive-variables-with-ref">Vue Composition API refs</a>).</p>
<p><strong>Out-of-the-box, Vue performs more granular updates</strong> so Vue updates are more performant by default. Of course, React has <code>React.memo</code> but that requires understanding of closures and when to use <code>React.useMemo</code> and <code>React.useCallback</code>.</p>
<p>Vue isn't off the hook though. Reactivity via injecting observables comes with <a href="https://v3.vuejs.org/guide/reactivity-fundamentals.html#destructuring-reactive-state">its</a> <a href="https://v3.vuejs.org/guide/composition-api-introduction.html#reactive-variables-with-ref">gotchas</a>.</p>
<h2>API surface area</h2>
<p>It's hard for me to be objective because I have a lot more familiarity with the React API. However, I still feel that React has a smaller API and fewer React-specific concepts to learn (ignoring concurrent mode and time-slicing).
A number of things are more convenient in Vue. Here are a few examples.
v-model
Vue has sugar for two-way data binding. It's quite nice.</p>
<pre><code class="language-js">// MyVueComponent
<div>
<input v-model="message" />
<p>{{ message }}</p>
</div>
Vue.extend({
data: {
message: ''
}
})
</code></pre>
<blockquote>
<p>The following is quoted from the <a href="https://reactjs.org/docs/two-way-binding-helpers.html">React docs</a>:
<em>In React, data flows one way: from owner to child. We think that this makes your app's code easier to understand. You can think of it as "one-way data binding."</em></p>
</blockquote>
<pre><code class="language-jsx">function MyReactComponent() {
const [message, setMessage] = React.useState('');
return (
<div>
<input
value={message}
onChange={e => setMessage(e.target.value)}
/>
<p>{message}</p>
</div>
);
}
</code></pre>
<p>Combining class names</p>
<p>Vue has special class and style handling. These properties get merged and
also handle object maps and arrays.</p>
<p><strong>Combining class names</strong> - Vue's magic vs React's reality</p>
<p><strong>Vue</strong> - Automatic merging, object syntax, arrays. Clean and declarative:</p>
<pre><code class="language-js"><!-- Parent sets base + conditional -->
<MyButton
baseClass="btn"
:class="{ 'btn-primary': isPrimary, 'btn-large': isLarge }"
:style="{ '--accent': accentColor }"
/>
<!-- Child component - auto-merges everything -->
<template>
<button :class="[baseClass, buttonClass]" :style="mergedStyle">
{{ label }}
</button>
</template>
<script>
export default {
props: ['baseClass', 'class', 'style']
}
</script>
</code></pre>
<p>React - Manual string building or third-party libs like clsx/classnames:</p>
<pre><code class="language-jsx">function MyButton({
className,
style,
isPrimary = false,
isLarge = false,
accentColor,
label = 'Button'
}) {
const baseClasses = clsx(
'btn',
{
'btn-primary': isPrimary,
'btn-large': isLarge
},
className // parent override
);
return (
<button
className={baseClasses}
style={{
'--accent': accentColor,
...style
}}
>
{label}
</button>
);
}
// Usage
<MyButton
isPrimary={isPrimary}
isLarge={true}
accentColor="#ff6b6b"
className="rounded shadow-lg"
/>
</code></pre>
<p>Reactivity Philosophy: Vue's built-in merging feels magical - pass :class="{ active: isActive }" and it auto-combines. React forces you to build the string yourself or add clsx (40kb). Vue = less typing, React = total control over the exact CSS string generated.</p>
<pre><code class="language-jsx"><button @click="count += 1">{{ count }}</button>
defineComponent({
reset() {
// This causes rerender
this.count = 0;
}
})
</code></pre>
<p>The fact that mutating what looks like a local variable causes a rerender is still a little beyond my comfort zone 🙂</p>
<h2>Vue as a framework</h2>
<p>React pitches itself as a library and Vue as a framework. The line is blurry but Vue does more out-of-the-box than React. Vue has transitions and animations built-in. It has blessed libraries for routing and state management (vuex).</p>
<p>React, as in the core React, focuses on only the rendering layer. The other pieces are provided by the ecosystem, which fortunately, is very vibrant.</p>
<p>With my limited experience, bootstrapping an app feels about the same both with vue-cli and create-react-app. I like Vue Single File Components, which allows you to define component-scoped CSS in the same file as the template and component logic.</p>
<h2>Not Too Different After All</h2>
<p>While I've focused on differences, <strong>React and Vue share core concepts</strong> that map cleanly between them:</p>
<table>
<thead>
<tr>
<th>Vue</th>
<th>React</th>
</tr>
</thead>
<tbody>
<tr>
<td><strong>Virtual DOM + JSX</strong></td>
<td><strong>Virtual DOM + JSX</strong></td>
</tr>
<tr>
<td><strong>Slots</strong></td>
<td><strong>Children</strong></td>
</tr>
<tr>
<td><strong>Props/Data</strong></td>
<td><strong>Props/State</strong></td>
</tr>
<tr>
<td><strong>Teleport</strong></td>
<td><strong>Portal</strong></td>
</tr>
</tbody>
</table>
<h2>Which One Should You Choose?</h2>
<p><strong>No definitive answer—it depends on your needs:</strong></p>
<p><strong>Choose React if:</strong></p>
<ul>
<li>You're a <strong>type system purist</strong> (TypeScript integration is superior)</li>
<li>Building <strong>large, multi-engineer codebases</strong> (purer JS approach, fewer global gotchas)</li>
<li>Need <strong>maximum ecosystem</strong> (React Native, huge hiring pool, render targets)</li>
</ul>
<p><strong>Choose Vue if:</strong></p>
<ul>
<li>You prefer <strong>HTML-first</strong> development (templates + progressive enhancement)</li>
<li>Building <strong>content-heavy sites</strong> with sprinkled interactivity</li>
<li>Onboarding <strong>non-JS-heavy developers</strong> (intuitive templates, less re-render thinking)</li>
</ul>
<p><strong>Reality check:</strong> Both make you productive. Vue feels <strong>magical</strong> for rapid prototyping. React feels <strong>predictable</strong> for enterprise scale.</p>
<blockquote>
<p><em>I still prefer React's explicitness, but Vue's DX is genuinely impressive.</em></p>
</blockquote>
<p><strong>Pick based on team skills + project needs, not framework wars.</strong></p>]]></content:encoded>
</item>
<item>
<title><![CDATA[Personal Development]]></title>
<link>http://irenaapp.de//blog-personal-development/</link>
<guid>http://irenaapp.de//blog-personal-development/</guid>
<pubDate>Tue, 20 Jan 2026 14:34:00 GMT</pubDate>
<description><![CDATA[Coding as Brain Development Coding isn't just a job skill, it's cognitive rocket fuel. Every line of JavaScript, every React component…]]></description>
<content:encoded><![CDATA[<h2>Coding as Brain Development</h2>
<p><strong>Coding isn't just a job skill, it's cognitive rocket fuel.</strong> Every line of JavaScript, every React component, every CSS Grid layout rewires your brain for <strong>systems thinking</strong> and <strong>pattern recognition</strong>. Debugging a props drilling issue forces you to trace data flows like a detective; optimizing a Vue computed property teaches you <strong>dependency analysis</strong>; building a responsive navbar drills <strong>spatial reasoning</strong> into your skull. Studies show programmers develop <strong>stronger working memory</strong> and <strong>superior problem decomposition</strong>—skills that transfer to business strategy, relationship dynamics, even chess.</p>
<p><strong>The real growth hack? Constraints breed creativity.</strong> When you're stuck with vanilla React (no Gatsby plugins, as you prefer), you learn <strong>first principles</strong>: "How does this actually work?" This mental model—breaking complex systems into atomic pieces—makes you dangerous across domains. Your Berlin React debugging sessions aren't "work"—they're <strong>neuroplasticity training</strong>. Write a movie library with perfect props flow? You've just leveled up <strong>logical reasoning</strong>. Fix a frontmatter date bug? That's <strong>precision under pressure</strong>.</p>
<p><strong>Personal development secret: Code to think, not to ship.</strong> Forget MVPs. Build toy projects that scare you: a custom GraphQL image handler, a CSS-only game, a markdown parser from scratch. Each failure etches <strong>resilience</strong> into your OS. Coding = meditation + gym + therapy. Your next commit isn't "done"—it's <strong>another neuron connection forged</strong>.</p>
<blockquote>
<p><em>The best developers don't code better—they think better. Stack those commits.</em></p>
</blockquote>
<h2>Coding: Executive Function Supercharger</h2>
<p><strong>Coding is executive function steroids.</strong> Debugging React props forces <strong>response inhibition</strong> (ignore that tempting <code>items.push()</code> mutation), planning the perfect movie library data flow builds <strong>working memory</strong> (hold component hierarchy + state shape in your head), tracing Vue reactivity chains hones <strong>cognitive flexibility</strong> (switch between template bugs and JS logic). Science shows just <strong>8 weeks of coding</strong> boosts planning accuracy by 30% and cuts inhibition errors—equivalent to 7 months of regular curriculum. Your Berlin React debugging marathons aren't "fixing bugs"—they're <strong>prefrontal cortex gym sessions</strong> .</p>
<h2>Memory Forged in Stack Traces</h2>
<p><strong>Every <code>console.log</code> etches memories into your hippocampus.</strong> Recalling React's exact props flow (<code>App → MovieGrid → MovieCard</code>), Vue's <code>ref.value</code> gotchas, or Gatsby's <code>.cache/</code> location requires <strong>episodic memory</strong> (what/where/when). Coding forces <strong>chunking</strong>—grouping <code>useState</code>, <code>useCallback</code>, <code>useMemo</code> into mental models—increasing your working memory capacity from 7±2 items to <strong>framework-sized architectures</strong>. Studies prove programmers have <strong>superior pattern recognition memory</strong>; your next <code>NaN</code> date fix isn't frustration—it's <strong>hippocampal hypertrophy</strong> .</p>
<h2>Coding: Your Brain's Ultimate Workout</h2>
<p><strong>Coding rewires your brain like nothing else.</strong> Every React props debug session strengthens your <strong>prefrontal cortex</strong> (planning, decision-making), every Vue reactivity puzzle boosts <strong>hippocampus activity</strong> (memory formation), every CSS Grid battle hones <strong>spatial reasoning</strong>. Science backs this: programmers show <strong>enhanced neural connectivity</strong> in logic centers, better <strong>working memory</strong>, and even <strong>delayed cognitive decline</strong>. That 3AM Berlin <code>NaN</code> date fix? You're literally building <strong>neuroplasticity</strong>—new brain pathways that make you smarter across <em>all</em> domains, from business strategy to emotional regulation .</p>
<h2>Personality Forged in the Commit Log</h2>
<p><strong>Your personality evolves with every <code>git push</code>.</strong> Debugging teaches <strong>stoic resilience</strong> (stack traces don't care about your feelings), refactoring builds <strong>intellectual humility</strong> (your first solution was probably wrong), shipping under deadlines forges <strong>execution grit</strong>. The coder who laughs at prop-drilling horror stories while sipping cold coffee? That's ** antifragility personified**—you grow <em>stronger</em> from production bugs. Coding doesn't just sharpen logic; it crafts <strong>calm-under-pressure confidence</strong> that radiates in meetings, negotiations, even first dates. Your terminal isn't a job tool—it's <strong>character armor</strong> .</p>
<h2>The Code Monk Mindset</h2>
<p><strong>Coding = modern stoicism.</strong> Every console.error is a chance to practice detachment—observe the bug without judgment, dissect it methodically, commit the fix. Your Gatsby cache nukes? Not failure, just data. React props not drilling? Not personal. This <strong>debugging zen</strong> spills into life: delayed trains in Berlin, project feedback, relationship friction. You learn to <strong>isolate variables</strong>, test hypotheses, iterate. The dev who stays calm when <code>NaN</code> dates flood the console can handle anything.</p>
<h2>Anti-Fragile Through Breaking</h2>
<p><strong>Growth lives in the stack trace.</strong> Comfortable codebases breed complacency. Force yourself into breakage: rip out <code>useContext</code> and prop-drill manually. Rewrite your movie library without <code>map()</code>. Ship CSS without Tailwind. Each self-inflicted wound carves <strong>deeper understanding</strong>. You're not "wasting time"—you're <strong>stress-testing your mental models</strong>. Real-world chaos (deploy failures, client changes) becomes trivial when you've already broken your own toys 100x.</p>
<h2>The 10x Comes from Boredom</h2>
<p><strong>Mastery paradox: The best code is boring.</strong> Your React props article—clean data flow, no magic, predictable bugs—is peak art. Personal growth isn't sexy frameworks or AI hype. It's the grind of <strong>making simple things flawless</strong>. Write the same todo app 10x with different constraints. Each iteration strips away cruft, reveals truth. Boredom is the <strong>signal</strong>—when <code>useState</code> feels trivial, you've internalized React's soul. That's when true creativity unlocks.</p>
<h2>Your Berlin Advantage</h2>
<p><strong>Cold winter,time for hurbal tea, wine and hot juzzy code.</strong> Berlin's gray skies force <strong>inward focus</strong>—perfect for deep coding marathons. No VC distractions, no Silicon Valley posturing. Just you, VSCode, and the problem. This <strong>monk-like environment</strong> breeds deliberate practice. Your React/Vue mental model battles aren't "blog posts"—they're <strong>philosophy papers</strong> refining how you see systems. Stack those commits in the dark months. Spring deploys will dazzle.</p>
<blockquote>
<p><em>Code to rewire your OS. Ship to pay rent. The commits are the compound interest.</em>
Pure cognitive fire—coding as brain gym, stoicism training, and Berlin winter survival. 💪🧠</p>
</blockquote>
<h2>The Debug Session That Ended My Book Club</h2>
<p><strong>I prop-drilled so obsessively, my friends staged an intervention.</strong></p>
<p>Picture this: Book club night. Everyone's discussing <em>Pride & Prejudice</em>. I interrupt:</p>
<p><em>"Wait—Elizabeth's arc flows like perfect props: Darcy (parent state) → Bennet sisters (children) → Lydia (uncontrolled mutation). But where's the Context Provider for entailment?!"</em></p>
<p>They stared. I opened VSCode. They left. My wine glass stayed—<strong>staring judgmentally at my terminal.</strong></p>
<p><strong>The hook:</strong> React and Vue both claim to fix this madness... but only one actually does. Guess which framework rescues you from becoming <em>that</em> developer?</p>
<p><em>Your cursor awaits. Don't make the wine glass judge you.</em>
Intelligent, relatable, coder-woman energy book club ruined by component trees! 📚💻😂
Winter continues</p>
<h2>Berlin Winter: Your Secret Weapon</h2>
<p><strong>Winter continues, but your code doesn't have to freeze.</strong> These dark Berlin months—when the sun sets at 3PM and U-Bahn platforms feel like tundra—gift you <strong>180 uninterrupted coding hours per month</strong>. No beach distractions, no rooftop parties. Just you, black coffee, and the glow of <code>localhost:8000</code>. Every fixed <code>NaN</code> date, every perfected props flow, every Vue vs React mental model battle carves <strong>winter-proof resilience</strong> into your brain. Spring deploys will hit like sunshine after 6 months of grind.</p>
<h2>The Commit That Warms You</h2>
<p><strong>Your next git push isn't "work"—it's central heating.</strong> Stack those React movie libraries, Vue className battles, personal dev manifestos. Each commit = <strong>1° warmer apartment</strong>, 1% sharper systems thinking, 1% closer to the developer who laughs at prop drilling horror stories instead of living them. Berlin winter rages outside, but your terminal? That's <strong>summer</strong>. Code through the cold. Ship when the snow melts.</p>
<blockquote>
<p><em>February deploy > February vacation. Stack the commits.</em></p>
</blockquote>
<p>Winter warrior energy, Berlin coding marathons as personal growth + survival fuel! ❄️💻🔥</p>]]></content:encoded>
</item>
<item>
<title><![CDATA[Docker vs Podman: Which One Should You Use in Production?]]></title>
<link>http://irenaapp.de//blog-docker-vs-podman-production/</link>
<guid>http://irenaapp.de//blog-docker-vs-podman-production/</guid>
<pubDate>Wed, 07 Jan 2026 19:10:00 GMT</pubDate>
<description><![CDATA[The real question behind “Docker vs Podman” Most teams don’t actually care about the logo on the CLI. They care about operational posture…]]></description>
<content:encoded><![CDATA[<h2>The real question behind “Docker vs Podman”</h2>
<img src="/docker-podman.png" alt="Docker vs Podman" style="float:left; width:240px; height:180px; object-fit:cover; margin:0.25rem 1rem 0.5rem 0; border-radius:6px;" />
<p>Most teams don’t actually care about the logo on the CLI. They care about <strong>operational posture</strong>: security boundaries, upgrade risk, compatibility with existing tooling, and how a container stack behaves under pressure. Docker and Podman both run OCI containers, but they make different architectural choices. Those choices matter in production.</p>
<p>This deep dive focuses on those choices and the practical tradeoffs they create.</p>
<h2>Architecture: daemon vs daemonless</h2>
<p><strong>Docker</strong> uses a long‑running daemon (<code>dockerd</code>) that manages images, containers, networks, and volumes. The CLI sends API requests to that daemon. The upside is a mature, centralized control plane with a stable API surface. The downside is a privileged process that becomes a single operational choke point.</p>
<p><strong>Podman</strong> is daemonless by design. The <code>podman</code> CLI directly creates containers via <code>conmon</code> and <code>runc</code> (or other OCI runtimes). This means fewer background processes, a smaller attack surface, and simpler systemd integration—but it also means you rely more on OS primitives and less on a single always‑on service.</p>
<p><strong>Production implication:</strong> Docker’s daemon model is easier to reason about at scale, while Podman’s daemonless model is simpler and more secure by default.</p>
<h2>Rootless containers and security posture</h2>
<p>Podman was designed with <strong>rootless operation</strong> as a first‑class capability. You can run containers as an unprivileged user with minimal friction, which reduces the blast radius of container escapes or misconfigurations. Docker supports rootless mode too, but historically it has been more complex to enable and less common in production teams.</p>
<p><strong>Production implication:</strong> If you are strict about least‑privilege and want rootless containers as a default, Podman is the cleaner fit.</p>
<h2>OCI compatibility: they both run the same containers</h2>
<p>Both Docker and Podman build and run <strong>OCI images</strong> and can pull from the same registries. From an image format perspective, they are interoperable.</p>
<p>The difference is in <strong>tooling expectations</strong>. Docker’s API and ecosystem are ubiquitous. Podman aims to be CLI‑compatible with Docker (<code>podman</code> vs <code>docker</code>), but not every tool that expects the Docker daemon socket will work without adaptation.</p>
<p><strong>Production implication:</strong> If you have tooling built around the Docker socket, Docker remains the path of least resistance.</p>
<h2>Networking: similar concepts, different defaults</h2>
<p>Docker’s networking is tightly integrated with its daemon. It offers a consistent bridge network model and a mature plugin ecosystem. Podman uses CNI (Container Network Interface) plugins or Netavark (newer stacks), which integrate well with Linux but require more explicit configuration in some cases.</p>
<p><strong>Production implication:</strong> Docker networking is smoother for common cases; Podman networking is more explicit and Linux‑native, but demands deeper familiarity when troubleshooting.</p>
<h2>Volumes and storage</h2>
<p>Both support volumes and bind mounts, but the operational model differs:</p>
<ul>
<li>Docker volumes are managed by the daemon, with consistent lifecycle commands.</li>
<li>Podman uses a more direct storage model through <code>containers/storage</code> and systemd integration.</li>
</ul>
<p><strong>Production implication:</strong> Docker is easier for teams who want standardized volume workflows; Podman is appealing if you already run systemd‑managed services and want a tighter OS integration.</p>
<h2>Compose vs Podman Compose</h2>
<p>Docker Compose is a first‑class citizen in Docker workflows. Podman has <code>podman-compose</code> (community‑driven) and systemd‑based alternatives. The feature set is solid for many use cases, but it is not always a drop‑in replacement for complex Compose stacks.</p>
<p><strong>Production implication:</strong> If your organization relies heavily on Compose, Docker is still more predictable. If you are comfortable with systemd or Kubernetes, Podman fits naturally.</p>
<h2>Operational ecosystem and support</h2>
<p>Docker has broad ecosystem support: CI/CD pipelines, IDE plugins, and cloud tooling often assume Docker. Podman is growing quickly, especially in enterprise Linux environments, but the assumption bias in tooling still favors Docker.</p>
<p><strong>Production implication:</strong> Docker is the safest compatibility choice; Podman is increasingly strong where security policies and Linux‑native stacks dominate.</p>
<h2>What I recommend in production</h2>
<ul>
<li><strong>Choose Docker</strong> when your tooling expects the Docker API, your team relies on Compose, or you need the widest ecosystem compatibility with minimal friction.</li>
<li><strong>Choose Podman</strong> when security posture and rootless operation are priorities, and your environment is already Linux‑native with systemd‑managed services.</li>
</ul>
<p>For most teams, Docker remains the shortest path to stable operations. For security‑first or enterprise Linux environments, Podman is an increasingly strong choice.</p>
<h2>A practical decision checklist</h2>
<ul>
<li>Do we depend on Docker socket‑based tooling? → <strong>Docker</strong></li>
<li>Do we want rootless by default? → <strong>Podman</strong></li>
<li>Do we run on enterprise Linux with strict security policies? → <strong>Podman</strong></li>
<li>Do we need maximum compatibility across dev/CI/prod? → <strong>Docker</strong></li>
</ul>
<p>The best choice is the one that matches your operational constraints, not the trend.</p>]]></content:encoded>
</item>
<item>
<title><![CDATA[Vue Methods used for Data Binding 🤔]]></title>
<link>http://irenaapp.de//blog-vue-methods/</link>
<guid>http://irenaapp.de//blog-vue-methods/</guid>
<pubDate>Tue, 06 Jan 2026 14:36:00 GMT</pubDate>
<description><![CDATA[Vue Methods for Data Binding In this article, we'll explore how to use Vue methods to efficiently handle data binding in your applications…]]></description>
<content:encoded><![CDATA[<h1>Vue Methods for Data Binding</h1>
<p>In this article, we'll explore how to use <strong>Vue methods</strong> to efficiently handle data binding in your applications.</p>
<h2>Methods vs Computed Properties</h2>
<p>Vue provides <strong>methods</strong> and <strong>computed properties</strong> for reactive data. Here's a quick overview:</p>
<ul>
<li><strong>Methods</strong> are called every time the component re-renders.</li>
<li><strong>Computed properties</strong> are cached based on their dependencies.</li>
</ul>
<pre><code class="language-javascript">export default {
data() {
return {
message: "Hello Vue!"
};
},
methods: {
reverseMessage() {
return this.message.split('').reverse().join('');
}
}
};
</code></pre>]]></content:encoded>
</item>
<item>
<title><![CDATA[Docker vs Docker Compose: What’s the Difference and Why You Need Both]]></title>
<link>http://irenaapp.de//blog-docker-vs-docker-compose-difference/</link>
<guid>http://irenaapp.de//blog-docker-vs-docker-compose-difference/</guid>
<pubDate>Sat, 03 Jan 2026 18:10:00 GMT</pubDate>
<description><![CDATA[The short version (for people who ship software) When teams ask “Docker vs Docker Compose, what’s the difference?”, they are really asking…]]></description>
<content:encoded><![CDATA[<h2>The short version (for people who ship software)</h2>
<p>When teams ask “Docker vs Docker Compose, what’s the difference?”, they are really asking how to move from <strong>a single container</strong> to <strong>a runnable system</strong> without drowning in manual commands. Docker is the engine that builds images and runs containers. Docker Compose is the orchestration layer that wires multiple containers together in a single, repeatable workflow. You don’t use one instead of the other. You use Docker to define the artifact and Compose to define the system.</p>
<h2>Images and containers: the prerequisite mental model</h2>
<p>Think of an image as a frozen artifact: it is built once and never mutated. It is the outcome of a Dockerfile — a deterministic set of layers that describe how your application is packaged, what it depends on, and how it should start. A container is the live, running instance of that image. It is mutable at runtime, but that mutability is disposable. If you delete the container, the image still exists and can be used to spawn a fresh, identical runtime. This image/container split is the core reason Docker feels predictable in production.</p>
<h2>What Docker actually does</h2>
<p>Docker is the underlying technology that does the heavy lifting: building images, caching layers, pulling and pushing artifacts, and launching containers. The Dockerfile is the contract between your code and your runtime. It states, step by step, how to build the image. When you run <code>docker build</code>, Docker executes the Dockerfile and produces an image that can be stored locally or pushed to a registry. When you run <code>docker run</code>, Docker creates and starts a container from that image. That is the fundamental loop: build once, run anywhere.</p>
<h2>Where Docker Compose fits (and why it exists)</h2>
<p>Compose exists because real applications are not a single container. They are a web app plus a database, a cache, a worker, maybe a queue. If you manage each container by hand, you end up with a pile of brittle commands, manual networking, and configuration drift. Docker Compose solves that by letting you describe the entire system in a single file. The <code>docker-compose.yml</code> file becomes the infrastructure blueprint for a local environment or a test stack. It says: here are the services, here is how they connect, and here is how to start them together with a single command.</p>
<h2>Why you need both a Dockerfile and a Compose file</h2>
<p>The Dockerfile defines <strong>how to build</strong> your application into a runnable artifact. The Compose file defines <strong>how to run</strong> that artifact alongside everything it depends on. If you only have a Dockerfile, you can build a container but you still have to manually wire it to databases, queues, and networks. If you only have Compose without a Dockerfile, you can only run prebuilt images and you lose control over how your application is packaged. Together, they create a clean separation: the Dockerfile is the build contract, the Compose file is the runtime contract.</p>
<h2>The real‑world workflow this enables</h2>
<p>In practice, the workflow becomes clean and repeatable. The Dockerfile packages your app once, in a way that is stable across machines. Compose then spins up the full environment with one command, including every dependency the app needs. This means onboarding a new developer is not a multi‑page setup guide; it is “run <code>docker compose up</code>.” It also means your test environment is not a snowflake; it is a declarative system that can be recreated at will.</p>
<h2>A concrete example: web + database</h2>
<p>Imagine a Django API paired with Postgres. You want to build the app from your Dockerfile, run the database as a managed image, and wire them together with a single command. This is exactly where Compose shines: it turns two separate containers into a single, coherent stack that can be started, stopped, and recreated as a unit without a checklist.</p>
<p>Here is a minimal <code>docker-compose.yml</code> that does that:</p>
<pre><code class="language-yaml">services:
web:
build: .
ports:
- "8000:8000"
environment:
- DATABASE_URL=postgres://postgres:postgres@db:5432/app
depends_on:
- db
db:
image: postgres:16
environment:
- POSTGRES_PASSWORD=postgres
volumes:
- db_data:/var/lib/postgresql/data
volumes:
db_data:
</code></pre>
<p>With this in place, <code>docker compose up --build</code> will build your app image, create a database container, attach them to the same network, and make the app available on port 8000. This is the moment Docker stops being a single‑container tool and becomes a system‑level workflow.</p>
<p>To make the example complete, here is a matching <code>Dockerfile</code> for the web service:</p>
<pre><code class="language-Dockerfile">FROM python:3.12-slim
WORKDIR /app
ENV PYTHONDONTWRITEBYTECODE=1 \
PYTHONUNBUFFERED=1
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt
COPY . .
CMD ["python", "manage.py", "runserver", "0.0.0.0:8000"]
</code></pre>
<p>This keeps the image deterministic, avoids Python bytecode noise, and binds the app to <code>0.0.0.0</code> so it is reachable from outside the container.</p>
<h2>When not to use Docker Compose</h2>
<p>Compose is ideal for local development, CI previews, and small multi‑service stacks. It is <strong>not</strong> a production orchestrator. Once you need multi‑host scheduling, autoscaling, rolling updates, secrets management, and policy enforcement, you should move to a dedicated orchestrator like Kubernetes or a managed PaaS. The senior move is knowing where Compose ends and where a real control plane begins.</p>]]></content:encoded>
</item>
<item>
<title><![CDATA[Containers and Volumes: A Deep Dive]]></title>
<link>http://irenaapp.de//blog-docker-containers-and-volumes-deep-dive/</link>
<guid>http://irenaapp.de//blog-docker-containers-and-volumes-deep-dive/</guid>
<pubDate>Sat, 03 Jan 2026 17:40:00 GMT</pubDate>
<description><![CDATA[Why this matters at a senior level Most Docker issues in production trace back to misunderstandings about container mutability and state…]]></description>
<content:encoded><![CDATA[<h2>Why this matters at a senior level</h2>
<p>Most Docker issues in production trace back to misunderstandings about <strong>container mutability</strong> and <strong>state persistence</strong>. The “hello world” mental model is not enough when you are designing systems that must survive redeploys, rollbacks, and failures. This article frames containers and volumes in the way you need to reason about them in real environments.</p>
<h2>Containers: ephemeral runtime over immutable images</h2>
<p>A <strong>container</strong> is a running process instantiated from an image. The image is immutable; the container adds a writable layer on top.</p>
<p>Key implications for architecture:</p>
<ul>
<li>You can scale horizontally by creating multiple containers from the same image.</li>
<li>Runtime changes live only in the container’s writable layer and vanish when the container is removed.</li>
<li>The filesystem is <strong>copy‑on‑write</strong>, so writes are not baked into the image.</li>
</ul>
<p>This is the foundation of immutable infrastructure: <strong>all durable change must happen outside the container</strong>.</p>
<h2>Isolation boundaries and why they matter</h2>
<p>Containers use kernel primitives (namespaces and cgroups) to isolate processes. This gives you dependency isolation, resource governance, and predictable runtime behavior.</p>
<p>Practical consequences:</p>
<ul>
<li>Multiple versions of the same dependency can coexist across services.</li>
<li>CPU and memory limits are enforced per workload.</li>
<li>Debugging is easier because the runtime is defined by the image, not the host.</li>
</ul>
<p>Isolation is strong but not absolute. Containers share the host kernel, so <strong>security posture and privilege boundaries</strong> still need to be designed intentionally.</p>
<h2>Service‑to‑service communication: isolation with intent</h2>
<p>Microservices are useless if they cannot communicate. Docker networking lets you control that explicitly:</p>
<ul>
<li>Only containers on the same network can resolve each other by name.</li>
<li>Lateral communication is constrained to declared networks.</li>
<li>You can segment workloads by environment or trust boundary.</li>
</ul>
<p>This is the default posture you want in production: <strong>isolate by default, connect deliberately</strong>.</p>
<h2>The container filesystem is disposable</h2>
<p>A container’s writable layer is designed to be thrown away. That is a feature, not a bug.</p>
<p>If you store state in the container filesystem, you will lose it on redeploy, scale‑down, or crash recovery.</p>
<p>This is why stateful services cannot rely on container storage alone.</p>
<h2>Volumes: persistent state with lifecycle decoupling</h2>
<p>A <strong>volume</strong> is managed by Docker but stored outside the container’s writable layer. It survives container removal and re‑creation.</p>
<p>This gives you:</p>
<ul>
<li><strong>Durability</strong>: state is not tied to a specific container instance.</li>
<li><strong>Portability</strong>: the same volume can be attached to replacement containers.</li>
<li><strong>Operational clarity</strong>: the data lifecycle is independent from the compute lifecycle.</li>
</ul>
<p>In practice, volumes are the standard for databases, queues, and any persistent service.</p>
<h2>Failure mode example: Postgres without a volume</h2>
<ul>
<li>Start a Postgres container.</li>
<li>Create schema and insert data.</li>
<li>Remove the container.</li>
</ul>
<p>Result: all data is gone because it lived in the container’s ephemeral layer.</p>
<p>Now add a volume and mount it to the database data directory. You can replace the container and the state remains intact. That separation of <strong>compute vs state</strong> is the core operational benefit.</p>
<h2>Storage choices: when to use what</h2>
<ul>
<li><strong>Volumes</strong>: production‑grade persistence; managed by Docker.</li>
<li><strong>Bind mounts</strong>: fast local development; host‑filesystem coupling.</li>
<li><strong>Tmpfs</strong>: in‑memory, volatile, useful for sensitive or high‑performance ephemeral data.</li>
</ul>
<p>In production, volumes should be your default. Bind mounts are generally a local‑dev tool.</p>
<h2>Operational best practices</h2>
<ul>
<li>Treat containers as disposable compute.</li>
<li>Externalize all state into volumes or managed services.</li>
<li>Avoid baking secrets into images or layers.</li>
<li>Document data directories explicitly in service manifests.</li>
<li>Use health checks to enable safe container replacement.</li>
</ul>
<p>This is the mindset that makes containerized systems predictable under load and during recovery.</p>
<h2>The mental model recruiters expect you to own</h2>
<ul>
<li><strong>Image</strong>: immutable artifact built once.</li>
<li><strong>Container</strong>: short‑lived runtime instance.</li>
<li><strong>Volume</strong>: persistent state that outlives containers.</li>
</ul>
<p>If you can explain those relationships clearly, you are already ahead of most candidates.</p>
<h2>Next steps if you want to go deeper</h2>
<ul>
<li>Inspect mount points with <code>docker inspect <container></code>.</li>
<li>Map Docker networks to Linux bridges and veth pairs.</li>
<li>Review copy‑on‑write behavior with <code>overlay2</code>.</li>
</ul>
<p>This is where Docker stops being a tool and becomes an architectural asset.</p>]]></content:encoded>
</item>
<item>
<title><![CDATA[Advanced React Patterns and Performance]]></title>
<link>http://irenaapp.de//blog-advanced-react-patterns/</link>
<guid>http://irenaapp.de//blog-advanced-react-patterns/</guid>
<pubDate>Thu, 23 Oct 2025 14:37:00 GMT</pubDate>
<description><![CDATA[Introduction As your React applications grow, simple component patterns and local state management can quickly become insufficient…]]></description>
<content:encoded><![CDATA[<h2>Introduction</h2>
<p>As your React applications grow, simple component patterns and local state management can quickly become insufficient. Developers often run into issues like <strong>prop drilling, unnecessary re-renders, and complex state management</strong>, which can make applications harder to maintain and slow to perform.</p>
<p>In this article, we’ll explore <strong>advanced React patterns</strong> that address these challenges. You’ll learn how to structure your components for scalability, manage complex state with hooks and context, and optimize performance using memoization, lazy loading, and reusable patterns. By the end, you’ll have a toolkit of strategies to write cleaner, faster, and more maintainable React applications.</p>
<h2>1. Prop Drilling vs Context – Sharing Data the Right Way</h2>
<p>In small apps, passing data down through props is straightforward. However, in larger apps, deeply nested components can make this approach cumbersome.</p>
<pre><code class="language-jsx">function Grandparent() {
const user = { name: 'Alice' };
return <Parent user={user} />;
}
function Parent({ user }) {
return <Child user={user} />;
}
function Child({ user }) {
return <p>Hello, {user.name}</p>;
}
This works, but updating user in many components can be tedious.
React Context solves this problem by providing a global state accessible to any nested component:
import { createContext, useContext } from 'react';
const UserContext = createContext();
function App() {
const user = { name: 'Alice' };
return (
<UserContext.Provider value={user}>
<DeepTree />
</UserContext.Provider>
);
}
function NestedComponent() {
const user = useContext(UserContext);
return <p>Hello, {user.name}</p>;
}
</code></pre>
<p>Use Context for global state, not for every single value, to avoid unnecessary re-renders.</p>
<h2>2. Performance Optimization with Hooks</h2>
<p>useMemo – Caching Expensive Calculations</p>
<p>When your component performs heavy calculations, useMemo prevents recalculating on every render:</p>
<pre><code class="language-jsx">import { useMemo, useState } from 'react';
function Expensive({ num }) {
const squared = useMemo(() => {
console.log('Calculating...');
return num ** 2;
}, [num]);
return <p>Result: {squared}</p>;
}
</code></pre>
<p>useCallback – Stable Function References</p>
<p>useCallback ensures functions maintain stable references, preventing unnecessary re-renders when passed as props:</p>
<pre><code class="language-jsx">const increment = useCallback(() => setCount(c => c + 1), []);
</code></pre>
<h2>3. Scalable State Management with useReducer + Context</h2>
<p>For complex state, combining useReducer with Context creates a predictable, maintainable pattern:</p>
<pre><code class="language-jsx">import { createContext, useContext, useReducer } from 'react';
const TodoContext = createContext();
const initialState = { todos: [] };
function reducer(state, action) {
switch (action.type) {
case 'add': return { todos: [...state.todos, action.payload] };
case 'remove': return { todos: state.todos.filter((_, i) => i !== action.index) };
default: return state;
}
}
export function TodoProvider({ children }) {
const [state, dispatch] = useReducer(reducer, initialState);
return <TodoContext.Provider value={{ state, dispatch }}>{children}</TodoContext.Provider>;
}
export function TodoList() {
const { state, dispatch } = useContext(TodoContext);
return (
<div>
{state.todos.map((todo, i) => (
<p key={i}>
{todo} <button onClick={() => dispatch({ type: 'remove', index: i })}>Remove</button>
</p>
))}
<button onClick={() => dispatch({ type: 'add', payload: 'New Task' })}>Add Todo</button>
</div>
);
}
</code></pre>
<p>This approach scales easily, even for large apps with complex state logic.</p>
<h2>4. Lazy Loading and Code Splitting</h2>
<p>React 18 supports dynamic imports to improve performance:</p>
<pre><code class="language-jsx">import { lazy, Suspense } from 'react';
const HeavyComponent = lazy(() => import('./HeavyComponent'));
export default function App() {
return (
<Suspense fallback={<p>Loading...</p>}>
<HeavyComponent />
</Suspense>
);
}
</code></pre>
<p>Lazy loading reduces initial bundle size, improving load times, especially in Gatsby static sites.</p>
<ol start="5">
<li>Reusable Component Patterns</li>
</ol>
<p>Container + Presentational: separates logic from UI.</p>
<p>Compound Components: share state implicitly between related components.</p>
<p>Custom Hooks: encapsulate reusable logic.</p>
<p>Example: Compound Tabs Component</p>
<pre><code class="language-jsx">function Tabs({ children }) {
const [active, setActive] = useState(0);
return children.map((child, i) =>
React.cloneElement(child, { isActive: i === active, onClick: () => setActive(i) })
);
}
function Tab({ isActive, onClick, children }) {
return <button style={{ fontWeight: isActive ? 'bold' : 'normal' }} onClick={onClick}>{children}</button>;
}
// Usage
<Tabs>
<Tab>Home</Tab>
<Tab>About</Tab>
<Tab>Contact</Tab>
</Tabs>
</code></pre>
<p>Advanced React patterns combine component composition, hooks, context, and performance optimization to solve real-world development challenges. By leveraging Context for global state, useReducer for complex logic, and memoization hooks like useMemo and useCallback, developers can build applications that are predictable, maintainable, and fast.</p>
<p>Lazy loading, code splitting, and reusable component patterns further enhance performance and scalability, ensuring that even large applications remain responsive and easy to maintain.</p>
<p>Mastering advanced React patterns is about more than just writing code—it’s about writing smart, maintainable, and performant code. Throughout this article, we explored how to structure components to prevent prop drilling, harness the power of Context for global state, and leverage useReducer for complex state management. These tools not only make your applications easier to maintain but also make state flows predictable, which is crucial as your app scales.</p>
<p>We also delved into performance optimization techniques. Using useMemo and useCallback ensures that expensive computations and functions do not trigger unnecessary re-renders, keeping your UI responsive. Lazy loading and code splitting with React.lazy and Suspense reduce initial load times, which is essential for modern web applications, particularly when building static or server-rendered sites with Gatsby v5.</p>
<p>Finally, we highlighted reusable component patterns such as container/presentational separation, compound components, and custom hooks. These patterns allow you to build modular, composable, and testable components that can easily adapt to evolving project requirements. By combining these approaches, you create a development workflow that emphasizes clarity, efficiency, and scalability.</p>
<p>In short, mastering these advanced patterns equips you with the skills to architect React applications like a pro—applications that are fast, maintainable, and ready for real-world production challenges. With React 18’s modern features and Gatsby v5’s performance-first capabilities, the strategies outlined here give you the foundation to build large-scale, high-performing, and future-proof web applications with confidence.</p>
<p>Happy coding!</p>]]></content:encoded>
</item>
<item>
<title><![CDATA[ React hooks practice]]></title>
<link>http://irenaapp.de//blog-react-hooks-practice/</link>
<guid>http://irenaapp.de//blog-react-hooks-practice/</guid>
<pubDate>Tue, 23 Sep 2025 14:37:00 GMT</pubDate>
<description><![CDATA[React is built around a unidirectional data flow, which makes component interactions predictable and easier to debug. Understanding how data…]]></description>
<content:encoded><![CDATA[<p>React is built around a unidirectional data flow, which makes component interactions predictable and easier to debug. Understanding how data travels through your application—from parent components to children via props, and how it can be shared globally via context—is essential for building scalable, maintainable frontend applications. With the introduction of hooks in React 16.8 and improvements in React 18, developers now have a more declarative and functional approach to managing state, effects, and context, replacing many of the patterns that previously required class components.</p>
<p>This article dives deep into React props, state management, hooks, and context, demonstrating practical patterns that can be used in real-world projects. You will learn not only how to pass data efficiently but also how to structure your components, share global state without prop drilling, and optimize your application for performance and maintainability. By the end, you’ll have a clearer understanding of how data flows in React applications and how to leverage modern hooks and context to write cleaner, more robust code.
React hooks are the foundation of modern React development. They allow you to <strong>use state, lifecycle methods, and other features</strong> without writing class components. Let’s explore how to apply hooks effectively.</p>
<h2>1. useState – Local State Management</h2>
<p><code>useState</code> lets you add state to functional components.</p>
<pre><code class="language-jsx">import { useState } from 'react';
export default function Toggle() {
const [isOn, setIsOn] = useState(false);
return (
<button onClick={() => setIsOn(!isOn)}>
{isOn ? 'ON' : 'OFF'}
</button>
);
}
</code></pre>
<p>Each component has its own isolated state.</p>
<h2>2. <code>useEffect</code> – Side Effects</h2>
<p>useEffect handles side effects like data fetching or subscriptions.</p>
<pre><code class="language-jsx">
import { useState, useEffect } from 'react';
export default function Timer() {
const [seconds, setSeconds] = useState(0);
useEffect(() => {
const interval = setInterval(() => setSeconds(s => s + 1), 1000);
return () => clearInterval(interval); // cleanup
}, []);
return <p>Seconds elapsed: {seconds}</p>;
}
</code></pre>
<p>The empty dependency array [] ensures the effect runs once on mount.</p>
<h2>3. Custom Hooks – Reusable Logic</h2>
<p>You can extract common logic into custom hooks.</p>
<pre><code class="language-jsx">import { useState, useEffect } from 'react';
function useWindowWidth() {
const [width, setWidth] = useState(window.innerWidth);
useEffect(() => {
const handleResize = () => setWidth(window.innerWidth);
window.addEventListener('resize', handleResize);
return () => window.removeEventListener('resize', handleResize);
}, []);
return width;
}
// Usage
export default function App() {
const width = useWindowWidth();
return <p>Window width: {width}px</p>;
}
</code></pre>
<p>Custom hooks start with use and let you share logic across components.</p>
<h2>4. <code>useReducer</code> – Complex State Logic</h2>
<p>For state that involves multiple values or complex updates, useReducer is helpful.</p>
<pre><code class="language-jsx">import { useReducer } from 'react';
const initialState = { count: 0 };
function reducer(state, action) {
switch(action.type) {
case 'increment': return { count: state.count + 1 };
case 'decrement': return { count: state.count - 1 };
default: return state;
}
}
export default function Counter() {
const [state, dispatch] = useReducer(reducer, initialState);
return (
<div>
<p>Count: {state.count}</p>
<button onClick={() => dispatch({ type: 'increment' })}>+</button>
<button onClick={() => dispatch({ type: 'decrement' })}>-</button>
</div>
);
}
</code></pre>
<p><code>useReducer</code>is similar to Redux but built into React.</p>
<p>Summary</p>
<p>In this post, we explored the foundational concepts of React’s data flow, starting with props as the simplest method of passing data down the component tree. We examined how useState allows components to maintain internal state, and how useEffect can handle side effects such as data fetching or subscriptions. Moving beyond local state, we looked at React Context, which enables global state sharing and eliminates cumbersome prop drilling, particularly in deep component trees.</p>
<p>We also highlighted the importance of combining hooks and context for scalable applications. Using useReducer with context, developers can manage complex state transitions in a predictable manner. Additionally, the post covered best practices for reusable and maintainable code, including custom hooks, clean component structure, and performance optimization.</p>
<p>Ultimately, mastering React’s data flow is about understanding how data moves, where it should live, and how to share it efficiently. By leveraging props, hooks, and context thoughtfully, developers can build applications that are not only functional but also scalable, maintainable, and performant, harnessing the full power of React 18 and modern frontend development patterns.</p>
<p>Happy coding!</p>]]></content:encoded>
</item>
<item>
<title><![CDATA[Neural Networks and algorythms]]></title>
<link>http://irenaapp.de//blog-neural-networks/</link>
<guid>http://irenaapp.de//blog-neural-networks/</guid>
<pubDate>Sun, 13 Jul 2025 14:37:00 GMT</pubDate>
<description><![CDATA[Neural Networks: How Machines Learned to Learn Neural networks are often presented as a sudden breakthrough—a mysterious leap that…]]></description>
<content:encoded><![CDATA[<h3>Neural Networks: How Machines Learned to Learn</h3>
<p>Neural networks are often presented as a sudden breakthrough—a mysterious leap that transformed computers into learning machines. In reality, they are the product of a long intellectual struggle to answer one deceptively simple question: Can learning itself be formalized?</p>
<p>Unlike traditional algorithms, which follow explicitly defined steps, neural networks represent a shift in how we think about computation. They do not merely execute instructions. They adapt. They approximate. They generalize. In doing so, they blur the boundary between programmed behavior and learned intelligence.</p>
<p>To understand neural networks is to understand one of the most profound changes in the history of computing.</p>
<h3>The Core Idea: Learning as Function Approximation</h3>
<p>At their heart, neural networks are mathematical systems designed to approximate functions. Given inputs and desired outputs, a network adjusts internal parameters—called weights—to minimize error. Over time, it learns a mapping from inputs to outputs without being explicitly told the rules.</p>
<p>This is a radical departure from classical programming.</p>
<p>In traditional software, a human specifies how a task should be performed. In neural networks, the human specifies what success looks like, and the system discovers how to achieve it. The algorithm no longer contains knowledge directly; it contains the capacity to acquire it.</p>
<h3>Biological Inspiration, Mathematical Reality</h3>
<p>Neural networks were inspired—loosely—by the structure of the human brain. Early researchers imagined artificial “neurons” that would activate when signals crossed certain thresholds. But modern neural networks are not biological simulations. They are mathematical abstractions.</p>
<p>Each artificial neuron performs a simple computation: it takes inputs, multiplies them by weights, sums them, and applies a nonlinear function. Individually, these operations are trivial. Collectively, across millions or billions of parameters, they give rise to astonishing complexity.</p>
<p>This mirrors a recurring theme in science: intelligence emerging from simple rules applied at scale.
The First Wave: The Perceptron and Early Optimism</p>
<p>In the 1950s, psychologist Frank Rosenblatt introduced the perceptron, one of the earliest neural network models. It could learn to classify simple patterns, and enthusiasm was high. Some researchers predicted machines with human-level intelligence within decades.</p>
<p>That optimism was premature.</p>
<p>The perceptron had severe limitations—it could not solve even basic problems like XOR. In 1969, Marvin Minsky and Seymour Papert highlighted these flaws, triggering what became known as an AI winter. Funding dried up. Neural networks fell out of favor.</p>
<p>For years, symbolic AI—rule-based systems—dominated the field.</p>
<h3>Backpropagation: The Algorithm That Changed Everything</h3>
<p>Neural networks returned not because of better metaphors, but because of a mathematical breakthrough.</p>
<p>In the 1980s, researchers refined and popularized backpropagation, an algorithm that efficiently computes how errors should be distributed backward through a network to update its weights. This made it feasible to train multi-layer networks—what we now call deep neural networks.</p>
<p>Backpropagation transformed neural networks from theoretical curiosities into practical tools. But the technology still faced constraints: limited data, slow hardware, and insufficient memory.</p>
<p>The idea was ahead of its time.</p>
<h3>Deep Learning and the Power of Scale</h3>
<p>The modern neural network revolution began in the 2010s, driven by three forces:</p>
<ul>
<li>
<p>Massive datasets generated by the internet</p>
</li>
<li>
<p>Powerful GPUs capable of parallel computation</p>
</li>
<li>
<p>Improved architectures like convolutional and transformer-based networks</p>
</li>
</ul>
<p>Suddenly, neural networks could scale.</p>
<p>Systems began outperforming humans in image recognition, speech transcription, and strategic games. DeepMind’s AlphaGo defeated world champions. Language models learned grammar, reasoning patterns, and creative expression—not because they were programmed to, but because such behaviors emerged during training.</p>
<p>This emergence remains one of the most philosophically unsettling aspects of neural networks.</p>
<h3>Neural Networks vs. Traditional Algorithms</h3>
<p>Traditional algorithms are explicit and interpretable. Neural networks are implicit and opaque.</p>
<p>This tradeoff is central to modern AI. Neural networks excel at tasks where rules are difficult to define but data is abundant—vision, language, pattern recognition. However, their internal reasoning is often inscrutable, leading to concerns about bias, reliability, and accountability.</p>
<p>In exchange for performance, we sacrifice transparency.</p>
<p>This tension defines much of today’s AI research.</p>
<h3>Do Neural Networks “Understand”?</h3>
<p>Neural networks do not understand in the human sense. They do not possess intention, consciousness, or subjective experience. Yet they exhibit behaviors that resemble understanding—translation, summarization, reasoning, and creativity.</p>
<p>This raises uncomfortable questions.</p>
<p>If a system produces coherent explanations, composes music, or generates novel ideas, does it matter whether it “understands” them? Or is functional behavior enough?</p>
<p>These questions echo debates raised nearly two centuries ago by Ada Lovelace, who argued that machines act within the scope of their instructions—but acknowledged that those instructions could grow unimaginably complex.</p>
<h3>Neural Networks as Cultural Infrastructure</h3>
<p>Today, neural networks are no longer experimental. They are infrastructure.</p>
<p>They shape what we see, what we buy, whom we meet, and how we communicate. They influence scientific discovery, economic opportunity, and political discourse. Their decisions scale faster than human oversight can easily follow.</p>
<p>This makes neural networks not just a technical subject, but a societal one.</p>
<p>Understanding how they work—and where they fail—is no longer optional.</p>
<h3>The Future: From Tools to Partners</h3>
<p>Neural networks will continue to evolve. Research is moving toward models that reason more explicitly, learn with less data, and integrate symbolic logic with statistical learning. Whether these systems will ever approach general intelligence remains an open question.</p>
<p>What is clear is this: neural networks represent a shift from programming machines to cultivating systems.</p>
<p>We no longer write intelligence line by line. We shape environments in which it can emerge.</p>
<p>That is both their promise—and their risk.</p>
<h3>My final thoughts: Learning Made Mechanical</h3>
<p>Neural networks are the culmination of a centuries-old ambition: to mechanize learning itself. They embody the idea that intelligence can arise from structured adaptation rather than explicit instruction. They are not minds. But they are mirrors—reflecting the data, values, and goals we embed within them.</p>
<p>The future of neural networks will not be decided solely by better architectures or larger models. It will be determined by how wisely we choose to use a technology that has learned, quite literally, from us.</p>
<p>And that responsibility, no matter how advanced our machines become, remains profoundly human.</p>
<h3>The Hidden Cost of Learning Machines</h3>
<p>Every advance in neural networks carries a price—one that is easy to overlook because it remains largely invisible to end users.</p>
<p>Modern neural networks do not run on abstraction alone. They consume vast amounts of electricity, much of it generated from fossil fuels. Training a single large-scale model can require megawatt-hours of energy, producing a carbon footprint comparable to that of entire households—or even small towns—over a year. Inference, too, is not free: every prompt, recommendation, and generated image draws power from data centers operating around the clock.</p>
<p>This environmental cost complicates the narrative of “intelligence as progress.” Neural networks replace some forms of human labor, but they also externalize energy consumption and environmental impact. What appears lightweight and instantaneous on a screen is supported by dense physical infrastructure: servers, cooling systems, global supply chains, and continuous power demand.</p>
<p>The irony is difficult to ignore. Systems designed to optimize efficiency often do so at the expense of planetary resources. As models grow larger, deeper, and more computationally intensive, their marginal gains in performance come with disproportionately higher energy costs.</p>
<p>This forces an uncomfortable question: How much intelligence can we afford?</p>
<p>The future of neural networks will depend not only on architectural innovation, but on sustainable computation—more efficient algorithms, greener energy sources, and a cultural shift away from treating scale as an unquestioned virtue. Intelligence that cannot coexist with its environment is not progress; it is merely extraction by another name.</p>]]></content:encoded>
</item>
<item>
<title><![CDATA[History of Artificial Inteligence]]></title>
<link>http://irenaapp.de//blog-history-ofcomputer-inteligence/</link>
<guid>http://irenaapp.de//blog-history-ofcomputer-inteligence/</guid>
<pubDate>Thu, 13 Mar 2025 14:37:00 GMT</pubDate>
<description><![CDATA[The Poetical Science: When Mathematics Meets Imagination Observing recent developments in machine learning and neural networks prompted me…]]></description>
<content:encoded><![CDATA[<p>The Poetical Science: When Mathematics Meets Imagination</p>
<p>Observing recent developments in machine learning and neural networks prompted me to reconsider their deeper intellectual origins. I found myself thinking further and further back in history—searching for the first mind that truly imagined the intelligence behind the machine. When traced far enough, the conceptual foundations of artificial intelligence point NOT to modern laboratories, but to Ada Lovelace’s early vision of machine intelligence.</p>
<p>Ada Lovelace’s intellectual formation was shaped by an unusual fear. The Victorian Visionary Who Predicted AI 200 Years Before ChatGPT
The World’s First Algorithm. Why It Matters More Than You Think?</p>
<h2>Let’s start with the facts.</h2>
<p>Ada Lovelace is widely recognized as the author of the world’s first computer algorithm—a set of instructions designed to be executed by Charles Babbage’s Analytical Engine, a mechanical computer that, notably, was never actually built in her lifetime.</p>
<p>The algorithm calculated Bernoulli numbers, a mathematical sequence known since the 17th century. But the true revolution wasn’t the math itself. It was the way Ada thought about the machine. Her algorithm introduced ideas no one had formalized before: conditional branching and looping. In modern terms, she invented the conceptual foundations of if–then logic and iteration. Without these, computers are glorified calculators. With them, they become programmable systems capable of solving an effectively infinite range of problems.</p>
<p>That alone would secure Ada Lovelace’s place in history.</p>
<p>But she didn’t stop there.
The Leap No One Else Made</p>
<p>In her notes on the Analytical Engine, Ada wrote:</p>
<blockquote>
<p>“The Analytical Engine might act upon other things besides number… Supposing, for instance, that the fundamental relations of pitched sounds in the science of harmony and of musical composition were susceptible of such expression and adaptations, the engine might compose elaborate and scientific pieces of music of any degree of complexity or extent.”</p>
</blockquote>
<p>Pause on that for a moment.</p>
<p>In 1843, while much of the world was still arguing about whether railways would cause physical harm to the human body, Ada Lovelace calmly proposed that machines could compose music.
She wasn’t describing automation. She wasn’t talking about faster arithmetic.</p>
<p>Her mother, Lady Byron, was determined that Ada would not inherit what she viewed as the dangerous emotional volatility and poetic excess of her father, Lord Byron—the most infamous Romantic poet of the 19th century. As a corrective, Ada was immersed in mathematics, logic, and scientific rigor from an early age. Poetry, in Lady Byron’s mind, was a liability. Mathematics was the cure.</p>
<p>Artificial intelligence did not begin with neural networks, GPUs, or Silicon Valley hype. It began as an idea—fragile, speculative, and deeply philosophical—long before the first computer ever powered on. When we talk about “intelligent machines” today, we often treat them as a sudden technological rupture. In reality, they are the result of a slow intellectual evolution spanning centuries, shaped as much by mathematicians, philosophers, and poets as by engineers.</p>
<p>What fascinates me is not how fast AI has advanced in recent years, but how early humans began imagining it. Long before algorithms could learn, thinkers were asking whether reasoning itself could be mechanized. Could logic be automated? Could creativity be formalized? Could a machine ever follow rules well enough to appear intelligent—or even creative? These questions predate modern computing, and they quietly laid the groundwork for everything we now call artificial intelligence.</p>
<p>This article traces the history of artificial intelligence not as a timeline of technologies, but as a lineage of ideas. From early symbolic logic and mechanical computation to the conceptual breakthroughs that made learning machines possible, I explore how intelligence was slowly transformed from a human-only trait into a computational problem. Understanding this history is not an academic luxury—it is essential if we want to understand what AI is today, what it is not, and what it may yet become.</p>
<p>History, of course, had other plans.</p>
<p>Rather than abandoning imagination, Ada fused it with formal reasoning. She described her approach as “poetical science”: a synthesis of disciplined logic and creative speculation. This hybrid way of thinking—neither purely technical nor purely artistic—became the defining feature of her genius.</p>
<p>Modern artificial intelligence development depends on precisely this mindset. The most impactful AI researchers are not only mathematicians or engineers; they are conceptual thinkers who can imagine systems that do not yet exist and then formalize those visions into executable structures. Ada Lovelace anticipated this intellectual posture more than a century before the field itself emerged.</p>
<p>Where Charles Babbage viewed the Analytical Engine primarily as a powerful calculator, Ada perceived something far more radical: a general-purpose machine, capable of operating on symbols, relationships, and abstractions. This insight prefigured Alan Turing’s formulation of the Universal Turing Machine by nearly a hundred years.</p>
<p>In contemporary AI terms, Ada understood what we now call generalization and transfer—the idea that a system designed for one domain can be repurposed across many. Babbage built a machine for calculation. Ada envisioned a platform for possibility.</p>
<h2>The Limits of Machines: Ada Lovelace’s Most Misunderstood Warning</h2>
<p>Ada Lovelace’s most quoted and most misinterpreted statement reads:</p>
<blockquote>
<p>“The Analytical Engine has no pretensions whatever to originate anything. It can do whatever we know how to order it to perform.”</p>
</blockquote>
<p>This sentence is often invoked as proof that Ada believed machines could never be creative. That interpretation is historically and philosophically shallow.</p>
<p>Ada was not making a metaphysical claim about machines in perpetuity. She was making a technical observation about the constraints of her era. Machines, she argued, could not originate beyond the scope of human instruction as it was then understood. But crucially, she left open the possibility that the nature of “ordering” itself could evolve.</p>
<p>In fact, her writings suggest she fully anticipated that increasingly sophisticated forms of instruction would yield increasingly complex and surprising outputs. The question she raised was not whether machines could produce novelty, but where responsibility for that novelty resides.</p>
<p>This is the same debate we are having today.
When a large language model generates a sentence it has never encountered before, is it creating—or executing probabilistic inference? When a system composes music based on harmonic constraints, is it expressing originality or recombining learned structure? Ada understood that the boundary between execution and creation is inherently unstable.</p>
<p>She never saw her algorithm run. Babbage never completed the Analytical Engine. Yet the theoretical framework she articulated shaped how later generations—from Turing to von Neumann to Hopper—conceptualized computation itself.
From Symbolic Logic to Neural Networks: Ada’s Enduring Legacy</p>
<p>Modern artificial intelligence bears Ada Lovelace’s intellectual fingerprints everywhere, often invisibly.</p>
<h3>1. Algorithmic Thinking as a Foundation</h3>
<p>Every machine learning pipeline—data preprocessing, training loops, optimization, inference—rests on the conceptual primitives Ada pioneered. Conditional logic, iteration, abstraction: neural networks do not eliminate these ideas; they scale them. Even the most advanced transformers rely on iterative computation and structured control flow.</p>
<h3>2. Creative Computation and Generative Models</h3>
<p>The rise of generative AI represents the direct realization of Ada’s most radical claim: that machines could manipulate symbols beyond numbers. Systems like GPT-4, Claude, Stable Diffusion, and Sora operationalize the very possibilities she imagined—machines composing text, images, and music from abstract representations.</p>
<h3>3. Responsibility and Ethical Agency</h3>
<p>Ada consistently emphasized human accountability. Machines, she argued, reflect the intent and limitations of their creators. In 2025, debates around AI alignment, bias, interpretability, and autonomous decision-making echo her concerns almost verbatim. The question has never been whether machines act—but who answers for their actions.</p>
<h3>4. Interdisciplinary Thinking as a Requirement</h3>
<p>Ada was neither merely a mathematician nor merely a visionary. She worked at the intersection of disciplines. Today’s breakthroughs in AI emerge from collaborations between computer science, neuroscience, linguistics, philosophy, and ethics. Ada understood, long before it was fashionable, that intelligence is not a single-domain problem.</p>
<p>She was imagining symbolic manipulation—the idea that a machine could operate on concepts, patterns, and abstractions, not just numbers. This is the intellectual leap that separates mechanical calculation from computation as we understand it today.</p>
<p>In other words, Ada wasn’t just programming a machine.
She was inventing the philosophy of software.</p>
<p>The First Person to See What Computers Could Become</p>
<p>Charles Babbage designed the hardware. Ada Lovelace understood the implications.</p>
<p>She grasped something that even many early 20th-century computer scientists would struggle with: that once information is encoded symbolically, a machine can process anything—music, language, logic, art—so long as the rules are well defined.</p>
<p>This insight makes Ada Lovelace arguably the first person to conceptualize general-purpose computing. Not faster math. Not better machines. But a new category of thinking.</p>
<p>It’s also why she rejected the idea that the machine could “think” in the human sense. She famously argued that the engine could only do what we know how to instruct it to do—a debate that still echoes today in discussions about AI consciousness and agency.
Why Ada Lovelace Feels Uncomfortably Relevant in 2026</p>
<h3>Why Ada Lovelace Disappeared—and Why She Returned</h3>
<p>For decades after her death at age thirty-six, Ada Lovelace faded from public memory. Babbage received credit. Her notes were dismissed as speculative or attributed to his influence. The reasons are familiar: gender bias, premature death, and work that could not be empirically validated in her lifetime.</p>
<p>But when computers finally materialized in the mid-20th century, scholars revisited her writings. What they found was not exaggeration, but foresight.</p>
<p>The U.S. Department of Defense named a programming language Ada in her honor. Computer historians recognized her as the first programmer. Ada Lovelace Day—celebrated each October—became a symbol of the women whose contributions to computing had been systematically overlooked.</p>
<p>In the age of AI, her relevance has only intensified.</p>
<h3>What Ada Lovelace Would Ask Us Today?</h3>
<p>If Ada Lovelace could observe modern artificial intelligence, she would not be surprised. She predicted this trajectory.</p>
<ul>
<li>
<p>But I presume she would ask difficult questions:</p>
</li>
<li>
<p>Who determines what the machine learns?</p>
</li>
<li>
<p>What happens when we no longer understand how it arrives at its conclusions?</p>
</li>
<li>
<p>Can creativity exist without intent?</p>
</li>
<li>
<p>What is lost when human imagination is outsourced to systems optimized for efficiency?</p>
</li>
</ul>
<p>These are not new questions. They are 19th-century questions wearing 21st-century clothes.</p>
<h3>My final thoughts: Vision and Execution Must Coevolve</h3>
<p>Fast-forward nearly two centuries.</p>
<p>We’re living in the age of ChatGPT, Claude, Midjourney, and generative systems that write poetry, compose music, design code, and create images from pure text. Entire industries are scrambling to redefine creativity, authorship, and intelligence.</p>
<p>And suddenly, Ada Lovelace doesn’t feel like a historical footnote.</p>
<ul>
<li>She feels like a warning—and a guide.</li>
</ul>
<p>She understood that the power of machines wouldn’t come from raw calculation, but from how humans choose to encode meaning. Today’s AI models don’t “understand” the world the way humans do—but neither did the Analytical Engine. What matters is the symbolic structure we give them and the feedback loops we allow them to form.</p>
<p>Ada foresaw a future where machines would extend human imagination rather than replace it. A future where creativity itself could be computational.</p>
<p>That’s not science fiction anymore.
The Real Legacy of the First Algorithm</p>
<p>Ada Lovelace didn’t just write the first algorithm.
She redefined what an algorithm could be for.</p>
<p>Her legacy isn’t a sequence of Bernoulli numbers. It’s the idea that computation is a creative act—that machines can participate in culture, not just commerce.</p>
<p>Every time an AI writes a poem, generates a melody, or helps a human think more clearly, it’s quietly proving her right.</p>
<p>Two hundred years ago, Ada Lovelace looked at a machine that didn’t exist and imagined a future that finally does.
Ada Lovelace teaches us something modern technology culture often forgets.</p>
<p>Execution without vision leads to powerful but purposeless systems.
Vision without execution fades into speculation.</p>
<p>Ada offered both.</p>
<p>She imagined machines not as replacements for human intelligence, but as extensions of it. She understood that the brilliance of a system is bounded by the imagination of those who design it.</p>
<p>In 2025, as artificial intelligence reshapes industries, labor, and creativity itself, Ada Lovelace’s legacy stands as both foundation and warning.</p>
<p>We have built the machines she imagined.
The remaining question is whether our vision is worthy of them.
And that, as Ada knew, is a human responsibility.</p>
<p>And we’re still catching up to her.</p>]]></content:encoded>
</item>
<item>
<title><![CDATA[History of Algorythms]]></title>
<link>http://irenaapp.de//blog-history-algotythms/</link>
<guid>http://irenaapp.de//blog-history-algotythms/</guid>
<pubDate>Thu, 13 Mar 2025 14:37:00 GMT</pubDate>
<description><![CDATA[Deep dive in Algorithms: How Human Thought Became Machine Logic Algorithms did not begin with computers. They began with a far older…]]></description>
<content:encoded><![CDATA[<h3>Deep dive in Algorithms: How Human Thought Became Machine Logic</h3>
<p>Algorithms did not begin with computers. They began with a far older question: Can human reasoning be reduced to a set of steps? Long before silicon chips and neural networks, thinkers across cultures tried to formalize decision-making, calculation, and logic itself. What we now call an “algorithm” is simply the latest expression of a deeply human desire—to make thinking reproducible.</p>
<p>Understanding the history of algorithms means understanding how abstraction, rules, and reasoning slowly escaped the human mind and became executable by machines.</p>
<h3>What an Algorithm Really Is</h3>
<p>At its core, an algorithm is a finite sequence of well-defined instructions designed to solve a problem or perform a task. That definition sounds modern, but the idea is ancient.</p>
<p>Any methodical recipe qualifies. So does long division. So does a legal procedure, a dance choreography, or a ritual. Algorithms are not inherently digital—they are structured thought.</p>
<p>Computers didn’t invent algorithms. They simply became the first entities fast and obedient enough to execute them at scale.</p>
<h3>Ancient Algorithms: Computation Before Computers</h3>
<p>Some of the earliest known algorithms come from Babylonian mathematics (circa 2000 BCE), where clay tablets describe step-by-step procedures for solving equations and calculating square roots. These were explicit, repeatable methods—algorithms in everything but name.</p>
<p>In ancient Greece, Euclid’s algorithm (circa 300 BCE) provided a systematic way to compute the greatest common divisor of two numbers. Remarkably, this algorithm is still taught today and remains foundational in number theory and cryptography.</p>
<p>Across the world, Indian mathematicians developed algorithms for arithmetic operations, while Chinese texts like The Nine Chapters on the Mathematical Art presented procedural problem-solving approaches that emphasized repeatability and abstraction.</p>
<p>These early algorithms shared a common trait: they were designed for human execution. Memory, speed, and error were limiting factors.</p>
<h3>Al-Khwarizmi and the Birth of the Algorithm</h3>
<p>The word algorithm itself comes from the name of the 9th-century Persian mathematician Muhammad ibn Musa al-Khwarizmi. His works introduced systematic methods for solving linear and quadratic equations and helped formalize arithmetic using Hindu-Arabic numerals.</p>
<p>Al-Khwarizmi’s influence was so profound that his name became synonymous with rule-based computation. Algorithms were no longer ad hoc tricks—they were generalizable procedures.</p>
<p>This was a turning point: algorithms began to detach from specific problems and move toward universal methods.</p>
<h3>Mechanical Thinking: When Algorithms Met Machines</h3>
<p>By the 17th century, thinkers like René Descartes and Gottfried Wilhelm Leibniz were obsessed with the idea that reasoning itself could be mechanized. Leibniz imagined a “calculus of thought” where disputes could be resolved through calculation rather than debate.</p>
<p>Mechanical calculators soon followed. Blaise Pascal and Leibniz built devices capable of performing arithmetic operations automatically. But these machines were rigid—they executed fixed operations, not flexible algorithms.</p>
<p>The real conceptual leap came in the 19th century.</p>
<h3>Ada Lovelace and the Algorithm as an Abstract Idea</h3>
<p>Charles Babbage’s Analytical Engine was the first design for a general-purpose computing machine. But it was Ada Lovelace who understood its deeper implications.</p>
<p>In 1843, Lovelace wrote what is widely considered the first computer algorithm—a method for calculating Bernoulli numbers. More importantly, she recognized that the machine could operate on symbols beyond numbers, provided those symbols could be formalized.</p>
<p>This was revolutionary.</p>
<p>Ada reframed algorithms as abstract structures, independent of any specific machine. Her insight laid the philosophical groundwork for software, long before hardware made it practical.</p>
<h3>The 20th Century: Formalizing Computation</h3>
<p>The early 20th century marked a shift from mechanical devices to theoretical rigor.</p>
<p>Alan Turing introduced the concept of the Universal Turing Machine, proving that a single machine could execute any algorithm given the right instructions.</p>
<p>Alonzo Church formalized computation through lambda calculus.</p>
<p>John von Neumann defined stored-program architecture, allowing algorithms to be treated as data.</p>
<p>Algorithms were no longer just procedures—they became objects of study. Questions about efficiency, complexity, and limits emerged. Some problems, researchers discovered, were computationally intractable. Others were undecidable.</p>
<p>This era gave rise to computer science as a discipline.
From Deterministic Algorithms to Learning Systems</p>
<p>For most of history, algorithms were deterministic: given the same input, they produced the same output.</p>
<h3>That changed in the late 20th century.</h3>
<p>Probabilistic algorithms, evolutionary algorithms, and machine learning introduced uncertainty, adaptation, and feedback. Algorithms no longer just followed rules—they updated themselves based on data.</p>
<p>Neural networks, inspired by biological systems, pushed this even further. Instead of explicitly programming logic, engineers defined architectures and learning rules. The algorithm’s behavior emerged through training.</p>
<p>This marked a profound shift: from algorithms as instructions to algorithms as processes.
Modern Algorithms: Invisible Architects of Reality</p>
<p>Today, algorithms curate news feeds, allocate credit, diagnose disease, recommend relationships, and generate art. Most operate invisibly, embedded within massive systems optimized for scale.</p>
<p>Yet their lineage is unmistakable.</p>
<p>Every modern algorithm—no matter how complex—descends from ancient procedural thinking. Loops, conditionals, abstraction, optimization: the same conceptual tools refined over millennia.</p>
<p>What has changed is not the idea of the algorithm, but its power and reach.
Why the History of Algorithms Matters Now</p>
<p>In an age of artificial intelligence, algorithms shape human experience in ways earlier thinkers could barely imagine. Understanding their history reminds us that algorithms are not neutral forces of nature—they are human artifacts, carrying assumptions, values, and limitations.</p>
<p>The future of algorithms will not be determined solely by faster hardware or larger datasets. It will be shaped by how we choose to formalize goals, define success, and encode meaning.</p>
<p>Algorithms began as a way to make thinking systematic.</p>
<p>They have become a way to make thinking scalable.</p>
<p>The question we now face is not whether algorithms will continue to evolve—but whether our wisdom will evolve alongside them.</p>]]></content:encoded>
</item>
<item>
<title><![CDATA[History of Algorythms]]></title>
<link>http://irenaapp.de//blog-history-algotythms/</link>
<guid>http://irenaapp.de//blog-history-algotythms/</guid>
<pubDate>Thu, 13 Mar 2025 14:37:00 GMT</pubDate>
<description><![CDATA[]]></description>
<content:encoded><![CDATA[]]></content:encoded>
</item>
<item>
<title><![CDATA[ React component architecture ]]></title>
<link>http://irenaapp.de//blog-react-context/</link>
<guid>http://irenaapp.de//blog-react-context/</guid>
<pubDate>Thu, 23 Jan 2025 14:37:00 GMT</pubDate>
<description><![CDATA[React's component architecture revolves around data flow and state management. Understanding how data travels from parent to child…]]></description>
<content:encoded><![CDATA[<p>React's component architecture revolves around <strong>data flow</strong> and <strong>state management</strong>. Understanding how data travels from parent to child components, and how to manage it with hooks and context, is essential for building scalable apps.</p>
<h2>1. Props – Passing Data Down</h2>
<p>Props are the simplest way to pass data from a parent component to its children.</p>
<pre><code class="language-jsx">// Button.jsx
export default function Button({ label, onClick }) {
return <button onClick={onClick}>{label}</button>;
}
// App.jsx
import Button from './Button';
export default function App() {
const handleClick = () => alert('Button clicked!');
return <Button label="Click Me" onClick={handleClick} />;
}
</code></pre>
<p>Props are read-only: a child cannot directly modify the parent’s data.</p>
<h2>2. State – Managing Local Component Data</h2>
<p>State allows components to manage dynamic data internally using useState.</p>
<pre><code class="language-js">import { useState } from 'react';
export default function Counter() {
const [count, setCount] = useState(0);
return (
<div>
<p>Count: {count}</p>
<button onClick={() => setCount(count + 1)}>Increment</button>
</div>
);
}
</code></pre>
<p>useState triggers a re-render when the state changes.</p>
<h2>3. Context – Sharing Data Across Components</h2>
<p>React Context allows you to share state without prop drilling.</p>
<pre><code class="language-jsx">
import { createContext, useContext, useState } from 'react';
const ThemeContext = createContext();
export function ThemeProvider({ children }) {
const [theme, setTheme] = useState('light');
return (
<ThemeContext.Provider value={{ theme, setTheme }}>
{children}
</ThemeContext.Provider>
);
}
export function ThemeToggle() {
const { theme, setTheme } = useContext(ThemeContext);
return (
<button onClick={() => setTheme(theme === 'light' ? 'dark' : 'light')}>
Current Theme: {theme}
</button>
);
}
// Usage in App.jsx
import { ThemeProvider, ThemeToggle } from './ThemeContext';
export default function App() {
return (
<ThemeProvider>
<h1>Hello React</h1>
<ThemeToggle />
</ThemeProvider>
);
}
</code></pre>
<p>Context is best for global data like theme, authentication, or user settings.</p>
<h2>4. Combining Hooks and Context</h2>
<p>Hooks like useState, useEffect, and useReducer often work hand-in-hand with context to manage complex state across your app.</p>
<pre><code class="language-jsx">import { useReducer, createContext, useContext } from 'react';
const CounterContext = createContext();
const initialState = { count: 0 };
function reducer(state, action) {
switch(action.type) {
case 'increment': return { count: state.count + 1 };
case 'decrement': return { count: state.count - 1 };
default: return state;
}
}
export function CounterProvider({ children }) {
const [state, dispatch] = useReducer(reducer, initialState);
return (
<CounterContext.Provider value={{ state, dispatch }}>
{children}
</CounterContext.Provider>
);
}
export function CounterControls() {
const { state, dispatch } = useContext(CounterContext);
return (
<div>
<p>Count: {state.count}</p>
<button onClick={() => dispatch({ type: 'increment' })}>+</button>
<button onClick={() => dispatch({ type: 'decrement' })}>-</button>
</div>
);
}
// App.jsx
import { CounterProvider, CounterControls } from './CounterContext';
export default function App() {
return (
<CounterProvider>
<h1>Global Counter</h1>
<CounterControls />
</CounterProvider>
);
}
</code></pre>
<ol start="5">
<li>Best Practices</li>
</ol>
<ul>
<li>
<p>Keep state local until you need it globally.</p>
</li>
<li>
<p>Use Context for cross-cutting concerns, not everything.</p>
</li>
<li>
<p>Use custom hooks to encapsulate reusable logic.</p>
</li>
<li>
<p>Keep components pure and declarative.</p>
</li>
</ul>
<p>React 18 and Gatsby v5 work seamlessly together, allowing you to combine server-side rendering, static site generation, and modern React features like concurrent mode.</p>
<p>React’s data flow may seem simple at first, but mastering props, state, hooks, and context is key to building scalable, maintainable frontend applications.</p>
<p>Happy Coding journey!</p>]]></content:encoded>
</item>
<item>
<title><![CDATA[Setting Default Props Values in React]]></title>
<link>http://irenaapp.de//blog-advanced-react-setting-values/</link>
<guid>http://irenaapp.de//blog-advanced-react-setting-values/</guid>
<pubDate>Sat, 23 Nov 2024 14:37:00 GMT</pubDate>
<description><![CDATA[Introduction In React, props are the primary way components receive data from their parents. They allow components to remain flexible and…]]></description>
<content:encoded><![CDATA[<h2>Introduction</h2>
<p>In React, <strong>props</strong> are the primary way components receive data from their parents. They allow components to remain <strong>flexible and reusable</strong>, but what happens when a parent component doesn’t provide a specific prop? Without defaults, your components can behave unpredictably or even break.</p>
<p>Setting <strong>default prop values</strong> ensures that your components always have meaningful data to work with, improving <strong>robustness, maintainability, and developer experience</strong>. This is especially important in large applications where components may be reused in multiple contexts, or when integrating with external data sources that may be incomplete or inconsistent.</p>
<p>In this post, we’ll explore <strong>how to define default props</strong> in React using both <strong>functional components</strong> and <strong>TypeScript</strong>, discuss best practices, and show how to combine them with <strong>destructuring and modern hooks</strong> for clean, readable code. By the end, you’ll have a clear understanding of how to safeguard your components with sensible defaults.</p>
<hr>
<h2>1. Setting Default Props in Functional Components</h2>
<p>In modern React (React 16.8+), functional components can define default prop values directly in the <strong>function parameter destructuring</strong>:</p>
<pre><code class="language-jsx">function Button({ label = 'Click Me', color = 'blue' }) {
return <button style={{ backgroundColor: color }}>{label}</button>;
}
// Usage
<Button /> // Renders a blue button with "Click Me"
<Button label="Submit" color="green" /> // Renders a green button with "Submit"
</code></pre>]]></content:encoded>
</item>
<item>
<title><![CDATA[How to use user input]]></title>
<link>http://irenaapp.de//blog-react-using-user-input/</link>
<guid>http://irenaapp.de//blog-react-using-user-input/</guid>
<pubDate>Sun, 23 Jun 2024 14:37:00 GMT</pubDate>
<description><![CDATA[User input is at the heart of every interactive application. From simple text fields to complex multi-step forms, the way an application…]]></description>
<content:encoded><![CDATA[<p>User input is at the heart of every interactive application. From simple text fields to complex multi-step forms, the way an application collects, processes, and responds to user input directly shapes the user experience. In React, handling user input isn’t just about reading values from the DOM, it’s about creating a predictable data flow where the UI always reflects the current state of the application.</p>
<p>For developers coming from vanilla JavaScript or jQuery, React’s approach to user input can feel unfamiliar at first. Inputs are no longer passive elements you query when needed; instead, they become controlled participants in your component’s state. This shift is intentional. By treating user input as part of your application state, React gives you consistency, debuggability, and fine-grained control over how data moves through your UI.</p>
<p>In this guide, we’ll take a deep dive into how user input works in React. We’ll explore controlled and uncontrolled components, event handling, form state management, validation patterns, and common pitfalls. Along the way, you’ll see how these concepts connect back to React’s core philosophy: a single source of truth and a UI that is always derived from state.</p>
<h3>Understanding Events in React</h3>
<p>React uses a synthetic event system that wraps the browser’s native events. While the API feels familiar, it provides cross-browser consistency and better performance.</p>
<pre><code class="language-jsx">function InputExample() {
function handleChange(event) {
console.log(event.target.value);
}
return <input type="text" onChange={handleChange} />;
}
</code></pre>
<p>The key takeaway is that React listens for events declaratively. You don’t manually attach or remove listeners — you describe what should happen when an event occurs.</p>
<h3>Controlled Components</h3>
<p>A controlled component is an input element whose value is driven entirely by React state.</p>
<pre><code class="language-jsx">import { useState } from 'react';
function ControlledInput() {
const [value, setValue] = useState('');
return (
<input
type="text"
value={value}
onChange={(e) => setValue(e.target.value)}
/>
);
}
</code></pre>
<p>Why controlled components matter:</p>
<p>React always knows the current value</p>
<p>Validation and formatting become trivial</p>
<p>The UI and state can never drift out of sync</p>
<p>This pattern is the default recommendation for most inputs in React applications.</p>
<h3>Uncontrolled Components</h3>
<p>Uncontrolled components let the DOM manage the input’s value. React accesses it only when needed, usually via refs.</p>
<pre><code class="language-jsx">import { useRef } from 'react';
function UncontrolledInput() {
const inputRef = useRef();
function handleSubmit() {
console.log(inputRef.current.value);
}
return (
<>
<input ref={inputRef} />
<button onClick={handleSubmit}>Submit</button>
</>
);
}
</code></pre>
<p>Uncontrolled inputs are useful when:</p>
<p>Migrating legacy code</p>
<p>Working with third-party libraries</p>
<p>Performance is critical and re-renders must be minimized</p>
<p>Handling Multiple Inputs</p>
<p>Real-world forms rarely have a single field. A common pattern is to store form data in an object.</p>
<pre><code class="language-jsx">function Form() {
const [formData, setFormData] = useState({
name: '',
email: ''
});
function handleChange(e) {
const { name, value } = e.target;
setFormData(prev => ({
...prev,
[name]: value
}));
}
return (
<>
<input name="name" value={formData.name} onChange={handleChange} />
<input name="email" value={formData.email} onChange={handleChange} />
</>
);
}
</code></pre>
<p>This approach scales cleanly and keeps related input state grouped together.</p>
<p>Input Validation Patterns</p>
<p>Validation can happen at multiple stages:</p>
<p>On change (instant feedback)</p>
<p>On blur (after the user leaves the field)</p>
<p>On submit (final validation)</p>
<pre><code class="language-jsx">
const isEmailValid = email.includes('@');
</code></pre>
<p>For complex forms, validation logic is often extracted into custom hooks or utility functions to keep components readable.</p>
<h3>Common Pitfalls</h3>
<p>Forgetting to set value on controlled inputs</p>
<p>Mutating state directly instead of using setters</p>
<p>Over-validating on every keystroke</p>
<p>Mixing controlled and uncontrolled patterns unintentionally</p>
<p>Understanding these pitfalls early prevents subtle bugs later.</p>
<h3>Final Thoughts</h3>
<p>Handling user input in React is less about syntax and more about mindset. When inputs are treated as state, your UI becomes predictable, testable, and easier to reason about. Whether you’re building a small form or a complex data-entry flow, these patterns scale with your application.</p>
<p>Happy coding, every great React app starts by listening carefully to its users ✨</p>]]></content:encoded>
</item>
<item>
<title><![CDATA[React advanced topics debouncing, performance]]></title>
<link>http://irenaapp.de//blog-react-advanced-topics/</link>
<guid>http://irenaapp.de//blog-react-advanced-topics/</guid>
<pubDate>Thu, 13 Jun 2024 14:37:00 GMT</pubDate>
<description><![CDATA[As React applications grow, the challenges you face change. Early on, the focus is on getting components to render and state to update…]]></description>
<content:encoded><![CDATA[<p>As React applications grow, the challenges you face change. Early on, the focus is on getting components to render and state to update correctly. But once your app starts handling real users, real data, and real scale, a different set of problems emerges: unnecessary re-renders, sluggish inputs, expensive computations, and UI that feels just slightly off.</p>
<p>Advanced React isn’t about learning new APIs for the sake of it — it’s about learning when not to do work. Performance optimization, debouncing, memoization, and render control all revolve around one core idea: doing just enough, at the right time, for the right reason.</p>
<p>A useful way to think about this is through a familiar, non-technical process: making sourdough bread. Great sourdough isn’t rushed. You don’t mix everything at once, bake immediately, and hope for the best. You let things rest, you control timing, and you avoid disturbing the dough more than necessary. React performance works the same way. The better you understand timing, dependency, and restraint, the better the final result.</p>
<h3>Rendering Is Like Mixing Dough</h3>
<p>Every render in React is like mixing your dough. Mixing is necessary, it develops structure — but overmixing destroys it.</p>
<p>In React, re-renders happen when:</p>
<p>State changes</p>
<p>Props change</p>
<p>A parent re-renders</p>
<p>Not all re-renders are bad. The problem starts when components re-render without producing any visible change.</p>
<pre><code class="language-jsx">function Counter({ count }) {
console.log('Rendered');
return <p>{count}</p>;
}
</code></pre>
<p>If this component renders frequently with the same count, you’re kneading dough that’s already ready.</p>
<p>React.memo — Let the Dough Rest</p>
<p>React.memo prevents re-rendering when props haven’t changed.</p>
<pre><code class="language-jsx">const Counter = React.memo(function Counter({ count }) {
return <p>{count}</p>;
});
</code></pre>
<p>This is like letting the dough rest between folds. You’re still making progress, just not disturbing what doesn’t need attention.</p>
<p>Use React.memo when:</p>
<p>A component renders often</p>
<p>Props are stable</p>
<p>Rendering is expensive</p>
<h3>useCallback — Reusing Ingredients</h3>
<p>In sourdough, you don’t reinvent flour every time you bake. In React, functions are ingredients — and recreating them unnecessarily causes downstream re-renders.</p>
<pre><code class="language-jsx">const handleClick = useCallback(() => {
setCount(c => c + 1);
}, []);
</code></pre>
<p>Without useCallback, a new function is created on every render, which can cause memoized children to re-render anyway.</p>
<p>Think of useCallback as reusing the same starter instead of creating a new one each bake.</p>
<p>useMemo — Expensive Calculations Need Time</p>
<p>Some computations are slow. You wouldn’t mill flour every time you want a slice of bread.</p>
<pre><code class="language-jsx">const filteredItems = useMemo(() => {
return items.filter(item => item.includes(search));
}, [items, search]);
</code></pre>
<p>useMemo caches results until dependencies change, reducing unnecessary work.</p>
<p>Use it when:</p>
<p>Computation is expensive</p>
<p>Dependencies change infrequently</p>
<p>The result feeds into rendering</p>
<p>Debouncing — Let the Dough Ferment</p>
<p>Debouncing is about waiting.</p>
<p>When a user types into a search box, firing logic on every keystroke is like baking dough after every fold — wasteful and messy.</p>
<pre><code class="language-jsx">
function useDebounce(value, delay) {
const [debounced, setDebounced] = useState(value);
useEffect(() => {
const id = setTimeout(() => setDebounced(value), delay);
return () => clearTimeout(id);
}, [value, delay]);
return debounced;
}
</code></pre>
<p>const debouncedSearch = useDebounce(search, 300);</p>
<p>This allows input to settle before triggering expensive effects like API calls.</p>
<h3>Debouncing is fermentation: patience produces better results.</h3>
<h3>Throttling — Controlled Folding</h3>
<p>While debouncing waits until activity stops, throttling limits how often something can happen.</p>
<h3>Use throttling for:</h3>
<ul>
<li>
<p>Scroll events</p>
</li>
<li>
<p>Resize handlers</p>
</li>
<li>
<p>Mouse movement</p>
</li>
</ul>
<p>It’s like folding dough every 30 minutes, not constantly, not never.</p>
<h3>Avoiding Premature Optimization</h3>
<p>Not every component needs memoization. Over-optimizing early is like obsessing over hydration percentages before you’ve learned to bake.</p>
<p>Rules of thumb:</p>
<ul>
<li>
<p>Measure first</p>
</li>
<li>
<p>Optimize hot paths</p>
</li>
</ul>
<p>Prefer readability until performance is proven to be a problem</p>
<h3>Debouncing: Letting Input Settle</h3>
<p>Debouncing is a technique that delays execution until a burst of activity has finished. Instead of reacting to every change, you wait for things to calm down before doing expensive work — like making API calls or filtering large datasets.</p>
<p>This is especially important for user input. When someone types into a search field, they don’t expect the application to react to each individual keystroke. They expect the system to respond once they’ve finished expressing intent.</p>
<p>Prevents unnecessary API calls</p>
<p>Reduces wasted computations</p>
<p>Improves perceived performance</p>
<p>Keeps the UI responsive</p>
<p>Mental model:
Debouncing is fermentation. You mix the ingredients, then you wait. Rushing the process ruins the result — patience allows complexity and flavor to develop naturally.</p>
<p>In React, debouncing creates a buffer between fast-changing input and slow, expensive side effects. This separation leads to calmer renders and more predictable behavior.</p>
<h3>Throttling: Controlled Folding</h3>
<p>While debouncing waits until activity stops, throttling limits how often an action can happen. It ensures that even during continuous activity, your logic runs at a controlled, steady pace.</p>
<p>Throttling is ideal for events that fire constantly but still need regular updates:</p>
<p>Scroll events</p>
<p>Resize handlers</p>
<p>Mouse or pointer movement</p>
<p>Window position tracking</p>
<p>Instead of firing hundreds of times per second, throttling enforces a rhythm.</p>
<p>Mental model:
Throttling is like folding sourdough every 30 minutes — not constantly, not never. You intervene just enough to guide the structure without destroying it.</p>
<p>In React apps, throttling prevents event-driven logic from overwhelming the render cycle and keeps animations, layouts, and measurements smooth.</p>
<h3>Avoiding Premature Optimization</h3>
<p>One of the most common mistakes in advanced React codebases is optimizing too early. Memoization, callbacks, and caching are powerful tools — but unnecessary complexity can make code harder to read, debug, and maintain.</p>
<p>Not every component needs to be optimized. Many renders are cheap, and React is already fast by default.</p>
<p>Rules of thumb:</p>
<p>Measure first — don’t guess</p>
<p>Optimize hot paths, not everything</p>
<p>Prefer readability until performance is proven to be a problem</p>
<p>Optimize based on user experience, not theoretical cost</p>
<p>Mental model:
Over-optimizing early is like obsessing over hydration percentages before you’ve learned how to bake bread. Precision only matters once the fundamentals are solid.</p>
<p>React’s Profiler is your thermometer — use it to understand what’s actually slow before changing your recipe.</p>
<h3>Mental Model: React as a Kitchen</h3>
<p>A strong mental model helps advanced concepts click faster and stick longer. One useful way to think about React is as a well-organized kitchen:</p>
<ul>
<li>
<p>State → your ingredients</p>
</li>
<li>
<p>Props → how ingredients move between components</p>
</li>
<li>
<p>Renders → preparation steps</p>
</li>
<li>
<p>Memoization → resting the dough</p>
</li>
<li>
<p>Debouncing → fermentation</p>
</li>
<li>
<p>Throttling → controlled folding</p>
</li>
</ul>
<p>When each step is intentional, the system feels effortless — even if there’s a lot happening behind the scenes.</p>
<p>Great applications, like great bread, aren’t rushed. They’re the result of discipline, timing, and restraint.</p>
<h3>Final Thoughts</h3>
<p>Advanced React topics aren’t about clever tricks or obscure APIs. They’re about understanding cause and effect — knowing when React does work, why it does it, and how to avoid doing the same work twice.</p>
<p>When you slow down renders, reuse computation intelligently, and respect the natural flow of data, your application becomes:</p>
<ul>
<li>
<p>Faster</p>
</li>
<li>
<p>More predictable</p>
</li>
<li>
<p>Easier to reason about</p>
</li>
<li>
<p>More pleasant to maintain</p>
</li>
</ul>
<p>Just like sourdough, the best results come from knowing when to act — and when to wait.</p>
<p>Happy coding, and may your renders be minimal and your UI perfectly risen ✨</p>]]></content:encoded>
</item>
<item>
<title><![CDATA[React advanced topics part two pizza refactoring]]></title>
<link>http://irenaapp.de//blog-react-advanced-part-two/</link>
<guid>http://irenaapp.de//blog-react-advanced-part-two/</guid>
<pubDate>Thu, 13 Jun 2024 14:37:00 GMT</pubDate>
<description><![CDATA[Refactor Part 1: Split Read and Write Concerns A small but important improvement is to split context into separate concerns. One simple…]]></description>
<content:encoded><![CDATA[<h2>Refactor Part 1: Split Read and Write Concerns</h2>
<p>A small but important improvement is to split context into separate concerns. One simple pattern:</p>
<p>A PizzaStateContext that only exposes the pizza config.</p>
<p>A PizzaActionsContext that only exposes the setters.</p>
<p>This alone doesn’t fully solve the “everything re-renders when pizza changes” problem, but it clarifies the mental model and makes it easier to evolve the architecture.</p>
<pre><code class="language-jsx">// src/context/PizzaContextSplit.tsx
import React, {
createContext,
useContext,
useState,
ReactNode,
} from 'react';
type PizzaSize = 'small' | 'medium' | 'large';
type PizzaBase = 'thin' | 'regular' | 'deep-dish';
type ToppingId =
| 'pepperoni'
| 'mushrooms'
| 'onions'
| 'olives'
| 'extra-cheese';
type PizzaConfig = {
size: PizzaSize | null;
base: PizzaBase | null;
toppings: ToppingId[];
};
type PizzaStateContextValue = PizzaConfig;
type PizzaActionsContextValue = {
setSize: (size: PizzaSize) => void;
setBase: (base: PizzaBase) => void;
toggleTopping: (topping: ToppingId) => void;
reset: () => void;
};
const PizzaStateContext = createContext<PizzaStateContextValue | undefined>(
undefined
);
const PizzaActionsContext = createContext<
PizzaActionsContextValue | undefined
>(undefined);
const defaultPizza: PizzaConfig = {
size: null,
base: null,
toppings: [],
};
export function PizzaProvider({ children }: { children: ReactNode }) {
const [pizza, setPizza] = useState<PizzaConfig>(defaultPizza);
const setSize = (size: PizzaSize) => {
setPizza(prev => ({ ...prev, size }));
};
const setBase = (base: PizzaBase) => {
setPizza(prev => ({ ...prev, base }));
};
const toggleTopping = (topping: ToppingId) => {
setPizza(prev => {
const hasTopping = prev.toppings.includes(topping);
return {
...prev,
toppings: hasTopping
? prev.toppings.filter(t => t !== topping)
: [...prev.toppings, topping],
};
});
};
const reset = () => setPizza(defaultPizza);
const actions: PizzaActionsContextValue = {
setSize,
setBase,
toggleTopping,
reset,
};
return (
<PizzaStateContext.Provider value={pizza}>
<PizzaActionsContext.Provider value={actions}>
{children}
</PizzaActionsContext.Provider>
</PizzaStateContext.Provider>
);
}
export function usePizzaState() {
const ctx = useContext(PizzaStateContext);
if (!ctx) {
throw new Error('usePizzaState must be used within PizzaProvider');
}
return ctx;
}
export function usePizzaActions() {
const ctx = useContext(PizzaActionsContext);
if (!ctx) {
throw new Error('usePizzaActions must be used within PizzaProvider');
}
return ctx;
}
</code></pre>
<pre><code class="language-jsx">// src/components/PizzaSizeSelector.tsx
import React from 'react';
import { usePizzaState, usePizzaActions } from '../context/PizzaContextSplit';
export function PizzaSizeSelector() {
const { size } = usePizzaState();
const { setSize } = usePizzaActions();
return (
<section>
<h2>Choose size</h2>
{(['small', 'medium', 'large'] as const).map(s => (
<button
key={s}
onClick={() => setSize(s)}
aria-pressed={size === s}
>
{s}
</button>
))}
</section>
);
}
</code></pre>
<pre><code class="language-jsx">
// src/components/ToppingsSelector.tsx
import React from 'react';
import { usePizzaState, usePizzaActions } from '../context/PizzaContextSplit';
const allToppings = [
{ id: 'pepperoni', label: 'Pepperoni' },
{ id: 'mushrooms', label: 'Mushrooms' },
{ id: 'onions', label: 'Onions' },
{ id: 'olives', label: 'Olives' },
{ id: 'extra-cheese', label: 'Extra Cheese' },
] as const;
export function ToppingsSelector() {
const { toppings } = usePizzaState();
const { toggleTopping } = usePizzaActions();
return (
<section>
<h2>Choose toppings</h2>
{allToppings.map(topping => {
const selected = toppings.includes(topping.id);
return (
<button
key={topping.id}
onClick={() => toggleTopping(topping.id)}
aria-pressed={selected}
>
{topping.label} {selected ? '✓' : ''}
</button>
);
})}
</section>
);
}
</code></pre>
<pre><code class="language-jsx">// src/components/OrderSummary.tsx
import React, { useMemo } from 'react';
import { usePizzaState, usePizzaActions } from '../context/PizzaContextSplit';
function calculatePrice(
size: 'small' | 'medium' | 'large' | null,
base: 'thin' | 'regular' | 'deep-dish' | null,
toppings: string[]
): number {
let price = 0;
if (size === 'small') price += 8;
if (size === 'medium') price += 10;
if (size === 'large') price += 12;
if (base === 'thin') price += 0;
if (base === 'regular') price += 1;
if (base === 'deep-dish') price += 2;
price += toppings.length * 1.5;
return price;
}
export function OrderSummary() {
const { size, base, toppings } = usePizzaState();
const { reset } = usePizzaActions();
const price = useMemo(
() => calculatePrice(size, base, toppings),
[size, base, toppings]
);
const isComplete = Boolean(size && base);
return (
<aside>
<h2>Order summary</h2>
<p>Size: {size ?? 'Not selected'}</p>
<p>Base: {base ?? 'Not selected'}</p>
<p>
Toppings:{' '}
{toppings.length
? toppings.join(', ')
: 'No toppings selected'}
</p>
<p>Total: ${price.toFixed(2)}</p>
<button onClick={reset}>Reset</button>
<button disabled={!isComplete}>
{isComplete ? 'Checkout' : 'Choose size & base first'}
</button>
</aside>
);
}
</code></pre>
<p>his is already nicer to read, but we still have one PizzaStateContext whose value is the full pizza object. Changing toppings still forces everyone who calls usePizzaState() to re-render.</p>]]></content:encoded>
</item>
<item>
<title><![CDATA[React advanced topics part two Co-locate State]]></title>
<link>http://irenaapp.de//blog-react-advanced-part-two-co-locate-state/</link>
<guid>http://irenaapp.de//blog-react-advanced-part-two-co-locate-state/</guid>
<pubDate>Thu, 13 Jun 2024 14:37:00 GMT</pubDate>
<description><![CDATA[Refactor Part 2: Co-locate State and Use Multiple Contexts In many real apps, the biggest win comes from not putting everything in a single…]]></description>
<content:encoded><![CDATA[<h3>Refactor Part 2: Co-locate State and Use Multiple Contexts</h3>
<p>In many real apps, the biggest win comes from not putting everything in a single context at all. Instead:</p>
<p>Local UI state stays local (isToppingsPanelOpen, isSizePopoverOpen, etc.).</p>
<p>Shared state is split into smaller contexts per concern.</p>
<p>For our Pizza Builder, a reasonable split could be:</p>
<p>PizzaConfigContext for the actual pizza choice (size, base, toppings).</p>
<p>PricingContext (or just a hook) for derived pricing logic.</p>
<p>Local state inside components for any purely visual toggles.</p>
<p>Here’s an example where size/base and toppings are separate contexts. This is a bit more verbose, but demonstrates the pattern.</p>
<pre><code class="language-jsx">
// src/context/PizzaSizeBaseContext.tsx
import React, {
createContext,
useContext,
useState,
ReactNode,
} from 'react';
type PizzaSize = 'small' | 'medium' | 'large';
type PizzaBase = 'thin' | 'regular' | 'deep-dish';
type SizeBaseState = {
size: PizzaSize | null;
base: PizzaBase | null;
};
type SizeBaseContextValue = {
state: SizeBaseState;
setSize: (size: PizzaSize) => void;
setBase: (base: PizzaBase) => void;
};
const SizeBaseContext = createContext<SizeBaseContextValue | undefined>(
undefined
);
export function SizeBaseProvider({ children }: { children: ReactNode }) {
const [state, setState] = useState<SizeBaseState>({
size: null,
base: null,
});
const setSize = (size: PizzaSize) => {
setState(prev => ({ ...prev, size }));
};
const setBase = (base: PizzaBase) => {
setState(prev => ({ ...prev, base }));
};
return (
<SizeBaseContext.Provider value={{ state, setSize, setBase }}>
{children}
</SizeBaseContext.Provider>
);
}
export function useSizeBase() {
const ctx = useContext(SizeBaseContext);
if (!ctx) {
throw new Error('useSizeBase must be used within SizeBaseProvider');
}
return ctx;
}
</code></pre>
<pre><code class="language-jsx">// src/context/PizzaToppingsContext.tsx
import React, {
createContext,
useContext,
useState,
ReactNode,
} from 'react';
type ToppingId =
| 'pepperoni'
| 'mushrooms'
| 'onions'
| 'olives'
| 'extra-cheese';
type ToppingsContextValue = {
toppings: ToppingId[];
toggleTopping: (topping: ToppingId) => void;
resetToppings: () => void;
};
const ToppingsContext = createContext<ToppingsContextValue | undefined>(
undefined
);
export function ToppingsProvider({ children }: { children: ReactNode }) {
const [toppings, setToppings] = useState<ToppingId[]>([]);
const toggleTopping = (topping: ToppingId) => {
setToppings(prev => {
const hasTopping = prev.includes(topping);
return hasTopping
? prev.filter(t => t !== topping)
: [...prev, topping];
});
};
const resetToppings = () => setToppings([]);
return (
<ToppingsContext.Provider
value={{ toppings, toggleTopping, resetToppings }}
>
{children}
</ToppingsContext.Provider>
);
}
export function useToppings() {
const ctx = useContext(ToppingsContext);
if (!ctx) {
throw new Error('useToppings must be used within ToppingsProvider');
}
return ctx;
}
</code></pre>
<p>Now the page composition becomes:</p>
<pre><code class="language-jsx">// src/pages/pizza-builder-optimized.tsx
import React from 'react';
import { SizeBaseProvider } from '../context/PizzaSizeBaseContext';
import { ToppingsProvider } from '../context/PizzaToppingsContext';
import { PizzaSizeSelector } from '../components/PizzaSizeSelectorOptimized';
import { ToppingsSelector } from '../components/ToppingsSelectorOptimized';
import { OrderSummaryOptimized } from '../components/OrderSummaryOptimized';
export default function PizzaBuilderOptimizedPage() {
return (
<SizeBaseProvider>
<ToppingsProvider>
<main>
<h1>Build your pizza (optimized)</h1>
<PizzaSizeSelector />
<ToppingsSelector />
<OrderSummaryOptimized />
</main>
</ToppingsProvider>
</SizeBaseProvider>
);
}
</code></pre>
<p>And consumers:</p>
<pre><code class="language-jsx">// src/components/PizzaSizeSelectorOptimized.tsx
import React from 'react';
import { useSizeBase } from '../context/PizzaSizeBaseContext';
export function PizzaSizeSelector() {
const { state, setSize } = useSizeBase();
const { size } = state;
return (
<section>
<h2>Choose size</h2>
{(['small', 'medium', 'large'] as const).map(s => (
<button
key={s}
onClick={() => setSize(s)}
aria-pressed={size === s}
>
{s}
</button>
))}
</section>
);
}
</code></pre>
<pre><code class="language-jsx">// src/components/ToppingsSelectorOptimized.tsx
import React from 'react';
import { useToppings } from '../context/PizzaToppingsContext';
const allToppings = [
{ id: 'pepperoni', label: 'Pepperoni' },
{ id: 'mushrooms', label: 'Mushrooms' },
{ id: 'onions', label: 'Onions' },
{ id: 'olives', label: 'Olives' },
{ id: 'extra-cheese', label: 'Extra Cheese' },
] as const;
export function ToppingsSelector() {
const { toppings, toggleTopping } = useToppings();
return (
<section>
<h2>Choose toppings</h2>
{allToppings.map(topping => {
const selected = toppings.includes(topping.id);
return (
<button
key={topping.id}
onClick={() => toggleTopping(topping.id)}
aria-pressed={selected}
>
{topping.label} {selected ? '✓' : ''}
</button>
);
})}
</section>
);
}
</code></pre>
<pre><code class="language-jsx">
// src/components/OrderSummaryOptimized.tsx
import React, { useMemo } from 'react';
import { useSizeBase } from '../context/PizzaSizeBaseContext';
import { useToppings } from '../context/PizzaToppingsContext';
function calculatePrice(
size: 'small' | 'medium' | 'large' | null,
base: 'thin' | 'regular' | 'deep-dish' | null,
toppings: string[]
): number {
let price = 0;
if (size === 'small') price += 8;
if (size === 'medium') price += 10;
if (size === 'large') price += 12;
if (base === 'thin') price += 0;
if (base === 'regular') price += 1;
if (base === 'deep-dish') price += 2;
price += toppings.length * 1.5;
return price;
}
export function OrderSummaryOptimized() {
const { state } = useSizeBase();
const { toppings, resetToppings } = useToppings();
const { size, base } = state;
const price = useMemo(
() => calculatePrice(size, base, toppings),
[size, base, toppings]
);
const isComplete = Boolean(size && base);
const handleReset = () => {
// reset size/base
// You can either lift a reset handler into a combined provider
// or call separate reset hooks; here we just show the idea.
window.location.reload(); // placeholder, see discussion below
};
return (
<aside>
<h2>Order summary</h2>
<p>Size: {size ?? 'Not selected'}</p>
<p>Base: {base ?? 'Not selected'}</p>
<p>
Toppings:{' '}
{toppings.length
? toppings.join(', ')
: 'No toppings selected'}
</p>
<p>Total: ${price.toFixed(2)}</p>
<button onClick={handleReset}>Reset</button>
<button disabled={!isComplete}>
{isComplete ? 'Checkout' : 'Choose size & base first'}
</button>
</aside>
);
}
</code></pre>
<p>When to Move to a Dedicated Store
Context works well for:</p>
<ul>
<li>
<p>A few shared values that many components need</p>
</li>
<li>
<p>Mostly read-heavy data with modest update frequency</p>
</li>
<li>
<p>Once your Pizza Builder turns into a full restaurant management system with:</p>
</li>
<li>
<p>A cart with many pizzas</p>
</li>
<li>
<p>User profiles</p>
</li>
<li>
<p>Inventory and admin panels</p>
</li>
<li>
<p>Analytics and cross-page state</p>
</li>
</ul>
<p>The mental model is the same as what we’ve practiced here: think in slices and owners. Context is the first step; a store is a scaling strategy when your pizza shop grows into a full platform.</p>
<p>Happy coding!</p>]]></content:encoded>
</item>
<item>
<title><![CDATA[React advanced state management]]></title>
<link>http://irenaapp.de//blog-react-state-management/</link>
<guid>http://irenaapp.de//blog-react-state-management/</guid>
<pubDate>Thu, 16 May 2024 14:37:00 GMT</pubDate>
<description><![CDATA[Context, state, and re-renders are where a “simple” React app quietly turns into a pizza kitchen with too many cooks shouting orders at each…]]></description>
<content:encoded><![CDATA[<p>Context, state, and re-renders are where a “simple” React app quietly turns into a pizza kitchen with too many cooks shouting orders at each other. In small apps you can get away with passing props down a couple of levels, but once you have a full Gatsby site with layouts, sections, widgets, and modals, you need a deliberate strategy for where state lives, who owns it, and how far its updates should ripple through the tree. Context, external stores (like Zustand or Redux Toolkit), and local component state all solve different problems, and choosing the wrong one can make every tiny change (like “extra cheese toggled”) trigger a cascade of pointless re-renders across your entire UI.
React's virtual DOM mechanism effectively updates the DOM, but needless re-renders can still cause performance issues. Re-rendering can be optimized to make sure that only the components that require it re-render, which improves application performance and responsiveness.</p>
<h3>Understanding Re-Rendering in React</h3>
<p>React's rendering process revolves around its component tree. When a component's state or props change, React re-renders that component and its child components. However, if not managed properly, this can lead to unnecessary re-renders, where components that didn’t experience any real changes also get re-rendered, wasting resources.
State management refers to the process of managing the state of an application. The state is a piece of an object that holds the data that can change over time and affect the looks(rendering) and behavior of the application.
React allows us to create dynamic web applications. Managing state in React can be a bit tricky, especially if you’re new to it, as it has multiple approaches to achieve state management rather than one solution. It provides built-in features like the “useState” hook for managing state at the component level and the Context API for global state management. Additionally, there is a pool of external libraries like Redux to handle more complex state management needs.
Why do we need state management solutions?
State management solutions are essential for addressing issues like prop drilling and data sharing between components. Prop drilling occurs when you need to pass state through many levels of components, which can make the codebase hard to maintain and understand.</p>
<p>Additionally, when multiple components need to share data, managing this state without a proper solution can become cumbersome and lead to inconsistencies. Effective state management solutions help to centralize and streamline state handling, making the application more predictable and easier to debug.</p>
<h3>Context API</h3>
<p>What is the Context API?
The Context API in React enables you to share data across multiple components without manually passing props down through each level of the component tree.</p>
<p>When to Use Context API
The Context API is best suited for scenarios where you need to share state across a small to medium-sized application (sometimes in more complex scenarios as well). It is more suitable for storing pieces of data like themes, localization, authentication state etc. that doesn’t change frequently.</p>
<p>Advantages & Disadvantages of Context API
Advantages:</p>
<p>Easy to implement and use
Already built into React
Simple syntax with less boilerplate</p>
<p>For this guide we’ll build a Pizza Builder where users compose their own pizza: size, base, toppings, and maybe a live price breakdown. In the naïve version, we’ll stick all the pizza state into one giant context at the top of the app and let every component subscribe to everything, so changing a single topping re-renders the entire page. Then we’ll refactor it: splitting context by concern (cart vs. pizza configuration), co-locating fast-changing state closer to where it’s used, and using memoization and context-splitting patterns so that the “Order Summary” doesn’t re-render just because the user hovers over a topping option.</p>
<p>By the end, you’ll see three concrete patterns:</p>
<p>Local component state for purely UI concerns (like “is the toppings panel open?”).
Lean, read-focused contexts for shared configuration (like the current pizza and selected toppings) instead of a “global mutable blob”.</p>
<p>When and why to graduate to a dedicated state library (Zustand/Redux) once your “pizza shop” grows into a full restaurant management system with inventory, users, and cross-page analytics.
Every step will come with Pizza Builder code examples in React 18 style (function components, hooks, no GraphQL), so you can drop them straight into your Gatsby v5 project and actually feel the difference in render behavior as you slice and serve your state.</p>
<h2>The Pizza Builder: Requirements</h2>
<p>We’ll work with a very concrete UI:</p>
<ul>
<li>A <strong>PizzaSizeSelector</strong> (Small, Medium, Large)</li>
<li>A <strong>PizzaBaseSelector</strong> (Thin, Regular, Deep Dish)</li>
<li>A <strong>ToppingsSelector</strong> (list of toppings, each toggleable)</li>
<li>An <strong>OrderSummary</strong> (selected options + price)</li>
<li>A <strong>CheckoutButton</strong> (disabled until pizza is valid)</li>
</ul>
<p>Conceptually, our state looks like this:</p>
<pre><code class="language-ts">type PizzaSize = 'small' | 'medium' | 'large';
type PizzaBase = 'thin' | 'regular' | 'deep-dish';
type ToppingId =
| 'pepperoni'
| 'mushrooms'
| 'onions'
| 'olives'
| 'extra-cheese';
type PizzaConfig = {
size: PizzaSize | null;
base: PizzaBase | null;
toppings: ToppingId[];
};
</code></pre>
<p>We need:</p>
<p>To update this config from multiple components</p>
<p>To compute a price from the current config</p>
<p>To avoid re-rendering everything on every tiny change</p>
<p>Naïve Version: One Giant Context for Everything
The usual “first attempt” is a single context at the top that holds all pizza state and all updater functions. This is simple to reason about, but it has a hidden cost: every consumer re-renders whenever any part of the context value changes.</p>
<p>Step 1: The Giant Pizza Context</p>
<pre><code class="language-jsx">
// src/context/PizzaContext.tsx
import React, { createContext, useContext, useState, ReactNode } from 'react';
type PizzaSize = 'small' | 'medium' | 'large';
type PizzaBase = 'thin' | 'regular' | 'deep-dish';
type ToppingId =
| 'pepperoni'
| 'mushrooms'
| 'onions'
| 'olives'
| 'extra-cheese';
type PizzaConfig = {
size: PizzaSize | null;
base: PizzaBase | null;
toppings: ToppingId[];
};
type PizzaContextValue = {
pizza: PizzaConfig;
setSize: (size: PizzaSize) => void;
setBase: (base: PizzaBase) => void;
toggleTopping: (topping: ToppingId) => void;
reset: () => void;
};
const PizzaContext = createContext<PizzaContextValue | undefined>(undefined);
const defaultPizza: PizzaConfig = {
size: null,
base: null,
toppings: [],
};
export function PizzaProvider({ children }: { children: ReactNode }) {
const [pizza, setPizza] = useState<PizzaConfig>(defaultPizza);
const setSize = (size: PizzaSize) => {
setPizza(prev => ({ ...prev, size }));
};
const setBase = (base: PizzaBase) => {
setPizza(prev => ({ ...prev, base }));
};
const toggleTopping = (topping: ToppingId) => {
setPizza(prev => {
const hasTopping = prev.toppings.includes(topping);
return {
...prev,
toppings: hasTopping
? prev.toppings.filter(t => t !== topping)
: [...prev.toppings, topping],
};
});
};
const reset = () => setPizza(defaultPizza);
const value: PizzaContextValue = {
pizza,
setSize,
setBase,
toggleTopping,
reset,
};
return (
<PizzaContext.Provider value={value}>
{children}
</PizzaContext.Provider>
);
}
export function usePizza() {
const ctx = useContext(PizzaContext);
if (!ctx) {
throw new Error('usePizza must be used within a PizzaProvider');
}
return ctx;
}
</code></pre>
<p>Step 2: Components That Use the Context</p>
<pre><code class="language-jsx">// src/components/PizzaSizeSelector.tsx
import React from 'react';
import { usePizza } from '../context/PizzaContext';
export function PizzaSizeSelector() {
const { pizza, setSize } = usePizza();
return (
<section>
<h2>Choose size</h2>
{(['small', 'medium', 'large'] as const).map(size => (
<button
key={size}
onClick={() => setSize(size)}
aria-pressed={pizza.size === size}
>
{size}
</button>
))}
</section>
);
}
</code></pre>
<pre><code class="language-jsx">// src/components/ToppingsSelector.tsx
import React from 'react';
import { usePizza } from '../context/PizzaContext';
const allToppings = [
{ id: 'pepperoni', label: 'Pepperoni' },
{ id: 'mushrooms', label: 'Mushrooms' },
{ id: 'onions', label: 'Onions' },
{ id: 'olives', label: 'Olives' },
{ id: 'extra-cheese', label: 'Extra Cheese' },
] as const;
export function ToppingsSelector() {
const { pizza, toggleTopping } = usePizza();
return (
<section>
<h2>Choose toppings</h2>
{allToppings.map(topping => {
const selected = pizza.toppings.includes(topping.id);
return (
<button
key={topping.id}
onClick={() => toggleTopping(topping.id)}
aria-pressed={selected}
>
{topping.label} {selected ? '✓' : ''}
</button>
);
})}
</section>
);
}
</code></pre>
<pre><code class="language-jsx">
// src/components/OrderSummary.tsx
import React, { useMemo } from 'react';
import { usePizza } from '../context/PizzaContext';
function calculatePrice(size: any, base: any, toppings: any[]): number {
let price = 0;
if (size === 'small') price += 8;
if (size === 'medium') price += 10;
if (size === 'large') price += 12;
if (base === 'thin') price += 0;
if (base === 'regular') price += 1;
if (base === 'deep-dish') price += 2;
price += toppings.length * 1.5;
return price;
}
export function OrderSummary() {
const { pizza, reset } = usePizza();
const { size, base, toppings } = pizza;
const price = useMemo(
() => calculatePrice(size, base, toppings),
[size, base, toppings]
);
const isComplete = Boolean(size && base);
return (
<aside>
<h2>Order summary</h2>
<p>Size: {size ?? 'Not selected'}</p>
<p>Base: {base ?? 'Not selected'}</p>
<p>
Toppings:{' '}
{toppings.length
? toppings.join(', ')
: 'No toppings selected'}
</p>
<p>Total: ${price.toFixed(2)}</p>
<button onClick={reset}>Reset</button>
<button disabled={!isComplete}>
{isComplete ? 'Checkout' : 'Choose size & base first'}
</button>
</aside>
);
}
</code></pre>
<p>And the page:</p>
<pre><code class="language-jsx">// src/pages/pizza-builder.tsx
import React from 'react';
import { PizzaProvider } from '../context/PizzaContext';
import { PizzaSizeSelector } from '../components/PizzaSizeSelector';
import { ToppingsSelector } from '../components/ToppingsSelector';
import { OrderSummary } from '../components/OrderSummary';
export default function PizzaBuilderPage() {
return (
<PizzaProvider>
<main>
<h1>Build your pizza</h1>
<PizzaSizeSelector />
<ToppingsSelector />
<OrderSummary />
</main>
</PizzaProvider>
);
}
</code></pre>
<p>This works, but there’s a subtle performance issue: every time any part of pizza changes, all three components re-render. Even if you just add a topping, the size selector re-renders. Even if you change size, the toppings list re-renders.</p>
<p>For a toy pizza page this is fine, but for a large Gatsby app with many widgets hanging off a big context, this pattern scales poorly.</p>
<p>The Core Problem: Context Value as a Single Changing Object
The reason is simple: PizzaContext.Provider receives a value object that contains pizza and all the setters. On every state change, pizza changes identity, and therefore the value object changes identity. All consumers re-render. You can’t “memo” your way out of this at the consumer level if they all use the same context.</p>
<p>The questions we want to answer:</p>
<p>Can we narrow which components re-render when?</p>
<p>Can we keep the API ergonomic without turning everything into prop-drilling?</p>
<p>When does it make sense to split things into a store (like Zustand) instead?
This we will find out in the next guide.</p>]]></content:encoded>
</item>
<item>
<title><![CDATA[Specificity in css]]></title>
<link>http://irenaapp.de//blog-css-specificity/</link>
<guid>http://irenaapp.de//blog-css-specificity/</guid>
<pubDate>Sun, 13 Aug 2023 14:37:00 GMT</pubDate>
<description><![CDATA[Hacks for dealing with specificity Rules are the children of principles. CSS specificity is the set of rules browsers use to determine which…]]></description>
<content:encoded><![CDATA[<h2>Hacks for dealing with specificity</h2>
<blockquote>
<p>Rules are the children of principles.</p>
</blockquote>
<p>CSS specificity is the set of rules browsers use to determine which CSS style is applied when multiple rules target the same element. The rule with the higher specificity value takes priority.</p>
<ul>
<li>Inline styles have the highest specificity.</li>
<li>ID selectors override class, attribute, and element selectors.</li>
<li>Class selectors override element and pseudo-element selectors.</li>
<li>sWhen specificity is equal, the rule written last is applied.</li>
</ul>
<p>As we’re all probably well aware by now, specificity is one of the quickest ways to get yourself in a tangle when trying to scale a CSS project: even if you have the most considered source order, and your rulesets cascade and inherit to and from each other perfectly, an overly-specific selector can completely undo all of it. Specificity throws a real curve-ball at a language which is entirely dependent upon source order. To make things worse, you can’t opt out of it, and the only way to deal with it is by getting more and more specific.</p>
<p>CSS specificity is one of those concepts that every frontend developer encounters early and then spends years slowly mastering. At first, it feels simple: some styles win, others lose. But as projects grow, selectors pile up, and stylesheets expand, specificity quietly becomes one of the biggest sources of confusion, bugs, and frustration in CSS codebases.</p>
<p>Specificity is the rule system the browser uses to decide <strong>which CSS declaration gets applied</strong> when multiple rules target the same element. It’s not about order alone, and it’s not about which rule looks more important it’s a precise scoring mechanism. Understanding how this system works is the difference between fighting CSS and working with it.</p>
<p>In this guide, we’ll take a deep dive into CSS specificity. We’ll break down how it’s calculated, why some selectors are harder to override than others, how common mistakes happen, and how to design CSS that stays predictable as your application grows.</p>
<h2>What Is CSS Specificity?</h2>
<p>Specificity is a ranking system that determines which CSS rule takes precedence when multiple rules apply to the same element.</p>
<p>When the browser encounters conflicting styles, it asks:</p>
<blockquote>
<p>“Which selector is more specific?”</p>
</blockquote>
<p>The rule with the highest specificity score wins.</p>
<p>This means:</p>
<ul>
<li>A later rule does <strong>not</strong> always win</li>
<li>A longer selector is <strong>not</strong> always stronger</li>
<li>A more detailed selector may still lose</li>
</ul>
<h2>How Specificity Is Calculated</h2>
<p>Specificity is calculated using four categories, often written as a tuple:</p>
<pre><code>(a, b, c, d)
</code></pre>
<p>From left to right, each category becomes less important.</p>
<h3>1. Inline Styles <code>(1, 0, 0, 0)</code></h3>
<p>Styles applied directly to an element via the <code>style</code> attribute.</p>
<pre><code class="language-html"><div style="color: red;"></div>
</code></pre>
<p>These styles override almost everything else and should be used sparingly.</p>
<h3>2. ID Selectors <code>(0, 1, 0, 0)</code></h3>
<p>Each ID selector adds one point to the second column.</p>
<pre><code class="language-css">#header {
background: black;
}
</code></pre>
<p>ID selectors are extremely specific and difficult to override, which is why they’re discouraged for styling.</p>
<h3>3. Class, Attribute, and Pseudo-class Selectors <code>(0, 0, 1, 0)</code></h3>
<p>This category includes:</p>
<ul>
<li><code>.class</code></li>
<li><code>[type="text"]</code></li>
<li><code>:hover</code>, <code>:focus</code>, <code>:active</code></li>
</ul>
<pre><code class="language-css">.button:hover {
background: blue;
}
</code></pre>
<p>This is the most commonly used and most flexible level of specificity.</p>
<h3>4. Type and Pseudo-element Selectors <code>(0, 0, 0, 1)</code></h3>
<p>Includes:</p>
<ul>
<li><code>div</code>, <code>p</code>, <code>section</code></li>
<li><code>::before</code>, <code>::after</code></li>
</ul>
<pre><code class="language-css">p {
line-height: 1.6;
}
</code></pre>
<p>These selectors are weak and easy to override.</p>
<h2>Specificity in Action</h2>
<pre><code class="language-css">p {
color: black;
}
.text {
color: blue;
}
#main .text {
color: red;
}
</code></pre>
<p>Even though <code>.text</code> comes later than <code>p</code>, <code>#main .text</code> wins because it has higher specificity.</p>
<h2>Common Specificity Mistakes</h2>
<h3>Over-Nesting Selectors</h3>
<pre><code class="language-css">.app .page .card .title span {
color: red;
}
</code></pre>
<p>Problems:</p>
<ul>
<li>High specificity</li>
<li>Fragile structure</li>
<li>Hard to override</li>
</ul>
<h3>Overusing ID Selectors</h3>
<p>ID selectors lock styles to a single element and make reuse difficult.</p>
<pre><code class="language-css">#submitButton {
background: green;
}
</code></pre>
<p>Once used, overriding usually requires more IDs or <code>!important</code>.</p>
<h3>Reaching for <code>!important</code></h3>
<pre><code class="language-css">.color {
color: red !important;
}
</code></pre>
<p><code>!important</code> bypasses the specificity system entirely and often creates long-term problems.</p>
<h2>Managing Specificity the Right Way</h2>
<h3>Prefer Class Selectors</h3>
<p>Classes offer the best balance between power and flexibility.</p>
<pre><code class="language-css">.cardTitle {
font-size: 1.2rem;
}
</code></pre>
<h3>Use Low-Specificity Selectors by Default</h3>
<p>Start simple and add specificity only when necessary.</p>
<pre><code class="language-css">:where(h1, h2, h3) {
margin-bottom: 0.5em;
}
</code></pre>
<p><code>:where()</code> adds <strong>zero specificity</strong>, making overrides easy.</p>
<h3>Control Specificity with <code>:is()</code> and <code>:where()</code></h3>
<pre><code class="language-css">:is(.primary, .secondary) {
padding: 1rem;
}
</code></pre>
<p>Use these tools intentionally to avoid specificity escalation.</p>
<h2>The Cascade Still Matters</h2>
<p>Specificity is only one part of CSS decision-making. When specificity is equal, the cascade applies:</p>
<ul>
<li>Later rules win</li>
<li>Styles closer to the element win</li>
</ul>
<p>Understanding specificity helps you predict when the cascade will apply — and when it won’t.</p>
<h2>Mental Model: Specificity as Weight</h2>
<p>Think of specificity as weight, not importance.</p>
<ul>
<li>IDs are heavy</li>
<li>Classes are balanced</li>
<li>Type selectors are light</li>
</ul>
<p>Once weight is added, it’s hard to remove. Build light by default.</p>
<h2>Final Thoughts</h2>
<p>CSS specificity is not something to memorize it’s something to design around. Clean CSS isn’t about winning specificity battles, but about avoiding them altogether.</p>
<p>By keeping selectors simple, favoring classes, and understanding how the browser makes decisions, you can write styles that scale gracefully and remain predictable over time.</p>
<p>Happy coding — and may your selectors stay light and your overrides intentional ✨</p>]]></content:encoded>
</item>
<item>
<title><![CDATA[Selectors css]]></title>
<link>http://irenaapp.de//blog-css-dynamic-values/</link>
<guid>http://irenaapp.de//blog-css-dynamic-values/</guid>
<pubDate>Sun, 23 Jul 2023 14:37:00 GMT</pubDate>
<description><![CDATA[CSS selectors target and select the HTML elements you want to style. They are often treated as a solved problem, something we learn once and…]]></description>
<content:encoded><![CDATA[<p>CSS selectors target and select the HTML elements you want to style. They are often treated as a solved problem, something we learn once and then rarely revisit. In reality, selectors are one of the most powerful and evolving parts of the CSS language. As modern frontend development shifts toward component-based architectures like React, selectors have quietly adapted, becoming less about global styling and more about expressing intent, state, and relationships within UI systems.</p>
<p>At the same time, styling on the web is no longer static. Values change at runtime. Components respond to props, user interaction, accessibility states, themes, and system preferences. The challenge is no longer how to style an element, but how to design a styling system that can respond dynamically without becoming fragile or over-coupled to JavaScript logic. This is where a deeper understanding of selectors, combined with modern CSS features becomes essential.</p>
<blockquote>
<p>Specifically, CSS selectors allow you to select multiple elements at once.</p>
</blockquote>
<p>They are helpful when you want to apply the same styles to more than one HTML element, because you will not repeat yourself by writing the same lines of code for different elements.</p>
<p>CSS selectors are also helpful when you want to make a change you only need to make the change in one place, which saves you a lot of time. CSS selectors are among the first things you need to learn when you first start writing CSS code. And there are many selectors available to choose from, along with several different ways to use them more than you may realize.
This guide explores how CSS selectors work in a world driven by dynamic values, particularly in React applications. We’ll look beyond basic class selectors and dive into attribute selectors, pseudo-classes, and newer relational selectors, then connect them to runtime data using CSS variables and data attributes. The goal is to show how CSS can remain declarative, expressive, and scalable even as your UI becomes increasingly dynamic.</p>
<p>Rather than positioning CSS and React as competing approaches to styling, this guide treats them as complementary tools. React handles data and state, while CSS — powered by smart selectors — handles presentation and behavior. When used together intentionally, they reduce complexity, minimize unnecessary re-renders, and lead to UI code that is easier to reason about, maintain, and evolve.</p>
<p>With that said, there is no need to worry, you do not have to memorize everything.</p>
<h3>Why CSS Selectors Still Matter in Modern Frontends?</h3>
<blockquote>
<p>CSS selectors are the grammar of the web’s visual language. Even as frameworks like React abstract UI into components, selectors remain the bridge between structure and style. Understanding them deeply lets you write smaller stylesheets, avoid specificity wars, and unlock dynamic styling patterns that scale.</p>
</blockquote>
<p>This guide connects classic CSS selectors with dynamic values, especially in React-driven apps, so you can confidently style components without fighting your tools.</p>
<h2>A Quick Mental Model</h2>
<p>Think of selectors as questions you ask the DOM:</p>
<p>Which elements look like this, are located here, or are in this state?</p>
<p>Dynamic values are answers that change depending on props, state, or runtime conditions.</p>
<p>Selectors decide where styles apply. Dynamic values decide how they look right now.
This cheat sheet covers the most commonly used selectors you need to know when starting out. Bookmark it so you can come back to it whenever you need a quick reminder when you are working on your next web design project.</p>
<h2>Simple CSS Selectors</h2>
<p>Selectors allow you to target and select specific parts of your document for styling purposes.</p>
<p>Simple selectors directly select one or more elements:</p>
<p>By using the universal selector <code>*</code>.
Based on the name/type of the element.
Based on the class value of the element.
Based on the ID value of the element.
By learning how the most simple selectors work, you can understand how to use the more complex ones.</p>
<p>The simple selectors will most often be the ones you will use the most and the ones you will be the most familiar with if you have some experience writing CSS code.</p>
<h2>CSS Universal Selector</h2>
<p>The universal selector, also known as a wildcard, selects everything - every single element in the document.</p>
<p>To use the universal selector, use the asterisk character, *.</p>
<pre><code class="language-css">* {
property: value;
}
</code></pre>
<p>You can use the universal selector to reset the browser's default padding and margin to zero at the top of the file before you add any other styles:</p>
<pre><code class="language-css">* {
padding: 0;
margin: 0;
}
</code></pre>
<h2>CSS Type Selector</h2>
<p>The CSS type selector selects all HTML elements of the specified type.</p>
<p>To use it, mention the name of the HTML element.</p>
<p>For example, if you wanted to apply a style to every single paragraph in the HTML document, you would specify the p element:</p>
<pre><code class="language-css">p {
property: value;
}
</code></pre>
<p>The code above matches and selects all p elements within the document and styles them.</p>
<p>Core Selector Types (Beyond the Basics)</p>
<ol>
<li>Attribute Selectors</li>
</ol>
<p>Attribute selectors shine when you want styles driven by data, not class sprawl.</p>
<pre><code class="language-css">button[aria-pressed="true"] {
background: black;
color: white;
}
</code></pre>
<p>Why this matters in React:</p>
<p>Props often map to attributes (aria-<em>, data-</em>)</p>
<p>Styling via attributes keeps logic and visuals loosely coupled</p>
<pre><code class="language-html"><button aria-pressed={isActive}>Toggle</button>
</code></pre>
<ol start="2">
<li>Pseudo-classes as State Machines</li>
</ol>
<p>Pseudo-classes are CSS’s built-in state system.</p>
<pre><code class="language-css">input:focus-visible {
outline: 2px solid dodgerblue;
}
</code></pre>
<p>Underrated ones worth memorizing:</p>
<p>:focus-visible</p>
<p>:focus-within</p>
<p>:has() (now shipping in modern browsers)</p>
<pre><code class="language-css">
.card:has(img:hover) {
transform: scale(1.02);
}
</code></pre>
<p>:where() adds zero specificity</p>
<p>:is() keeps the highest specificity of its arguments</p>
<p>Use them intentionally to avoid cascading chaos.</p>
<p>Dynamic Values with CSS Variables</p>
<p>CSS custom properties are the missing link between React props and pure CSS.</p>
<p>Defining Variables at the Component Boundary</p>
<pre><code class="language-html"><div style={{ '--accent': color }} className="card" />
</code></pre>
<pre><code class="language-css">.card {
border-left: 4px solid var(--accent);
}
</code></pre>
<p>Why this pattern scales:</p>
<p>CSS stays declarative</p>
<p>React only passes values, not styles</p>
<p>Themes become trivial</p>
<h2>Variables Beat Inline Styles</h2>
<p>Inline styles:</p>
<p>Don’t support pseudo-classes</p>
<p>Don’t cascade</p>
<p>Don’t compose</p>
<p>CSS variables:</p>
<p>Work with :hover, :focus, media queries</p>
<p>Cascade naturally</p>
<p>Are runtime-dynamic</p>
<pre><code class="language-css">.card:hover {
background: color-mix(in srgb, var(--accent), white 80%);
}
</code></pre>
<h2>Data Attributes as a Styling API</h2>
<p>Data attributes are a clean contract between logic and style.</p>
<pre><code class="language-html"><div data-variant="warning" />
</code></pre>
<pre><code class="language-css">[data-variant="warning"] {
background: #fff3cd;
color: #664d03;
}
</code></pre>
<p>This pattern:</p>
<p>Avoids class name explosions</p>
<p>Reads like documentation</p>
<p>Works across frameworks</p>
<p>Selectors in a Component World
The Mistake: Styling Components Like Pages</p>
<p>Over-nesting:</p>
<pre><code class="language-css">.app .page .card .title span {
color: red;
}
</code></pre>
<p>The fix:</p>
<p>Style components, not DOM paths</p>
<p>Prefer flat selectors with clear ownership</p>
<pre><code class="language-css">.cardTitle {
color: red;
}
</code></pre>
<p>Then enhance with state selectors, not structure.</p>
<p>When to Reach for CSS-in-JS (and When Not To)</p>
<p>CSS-in-JS is great when:</p>
<p>Styles are tightly coupled to logic</p>
<p>You need JS math or conditions</p>
<p>Traditional CSS + variables wins when:</p>
<p>Styles depend on state but not logic</p>
<p>You want browser-native performance</p>
<p>A hybrid approach is often the sweet spot.
A Practical Rule of Thumb</p>
<p>Selectors decide scope and state</p>
<p>Variables carry dynamic values</p>
<p>React props only pass data, not decisions</p>
<p>If your component API feels clean, your CSS probably is too.</p>
<h3>CSS Class Selector</h3>
<p>The class selector matches and selects HTML elements based on the value of their given class. Specifically, it selects every single element in the document with that specific class name.</p>
<p>With the class selector, you can select multiple elements at once and style them the same way without copying and pasting the same styles for each one separately.</p>
<p>Classes are reusable, making them a good option for practicing DRY development. DRY is a programming principle and is short for 'Don't Repeat Yourself'. As the name suggests, the aim is to avoid writing repetitive code whenever possible.</p>
<p>To select elements with the class selector, use the dot character, ., followed by the name of the class.</p>
<pre><code class="language-css">
.my_class {
property: value;
}
</code></pre>
<p>In the code above, elements with a class of my_class are selected and styled accordingly.</p>
<h3>CSS ID Selector</h3>
<p>The ID selector selects an HTML element based on the value of its ID attribute.</p>
<p>Keep in mind that the ID of an element should be unique in a document, meaning there should only be one HTML element with that given ID value. You cannot use the same ID value on a different element besides that one.</p>
<p>To select an element with a specific ID, use the hash character, #, followed by the name of the ID value:</p>
<pre><code class="language-css">#my_id {
property: value;
}
</code></pre>
<p>The code above will match only the unique element with the ID value of <code>my_id </code>.</p>
<p>It's worth mentioning that it is best to try and limit the use of this selector and opt for using the class selector instead. Applying styles using the ID selector is not ideal because the styles are not reusable.</p>
<p>Simple CSS selectors form the foundation of everything you do in CSS. Universal, type, class, and ID selectors may look basic on the surface, but they shape how you think about structure, reuse, and intent when styling a document. Mastering these selectors isn’t about memorizing syntax — it’s about understanding how CSS sees your HTML and how styles flow through the document.</p>
<p>In practice, you’ll find yourself relying heavily on class selectors, occasionally using type selectors for global patterns, and reaching for the universal selector with care. ID selectors, while powerful, often introduce rigidity and specificity issues when overused. Learning when not to use a selector is just as important as knowing how it works. These early decisions directly affect how scalable, maintainable, and flexible your styles become as a project grows.</p>
<p>Once these simple selectors feel intuitive, more advanced selector patterns start to make sense naturally. You begin to see CSS not as a list of rules, but as a system for expressing relationships, state, and meaning within your UI. This mental shift is what allows you to write cleaner stylesheets and avoid fighting the cascade later on.</p>
<p>In the next guide, we’ll take a deeper dive into attribute selectors — a powerful and often overlooked tool that allows you to style elements based on their attributes and values. Attribute selectors open the door to more semantic, data-driven styling and pair especially well with modern frameworks like React. If simple selectors are the vocabulary of CSS, attribute selectors are where the language really starts to get expressive.</p>
<p>Happy coding, and enjoy the journey of turning simple selectors into powerful styling tools,
and remember: clean selectors today mean fewer headaches tomorrow.</p>]]></content:encoded>
</item>
<item>
<title><![CDATA[Inheritance in css]]></title>
<link>http://irenaapp.de//blog-css-inheritance/</link>
<guid>http://irenaapp.de//blog-css-inheritance/</guid>
<pubDate>Fri, 21 Jul 2023 14:37:00 GMT</pubDate>
<description><![CDATA[CSS inheritance is one of the most fundamental and most misunderstood concepts in styling the web. At first glance, it feels almost…]]></description>
<content:encoded><![CDATA[<p>CSS inheritance is one of the most fundamental and most misunderstood concepts in styling the web. At first glance, it feels almost invisible: some styles seem to automatically apply to child elements, while others do not. As projects grow, this quiet behavior can either work in your favor or become a source of subtle bugs and confusion.</p>
<p>Inheritance defines how certain CSS properties flow from parent elements down to their children. It’s not random, and it’s not magic — it’s a deliberate part of the CSS design that helps reduce repetition, keep styles consistent, and make large documents easier to manage. Understanding what <em>does</em> inherit, what <em>doesn’t</em>, and why is essential to writing clean, predictable CSS.</p>
<p>In this guide, we’ll take a deep dive into CSS inheritance. We’ll explore how it works, which properties inherit by default, how inheritance interacts with the cascade and specificity, and how you can control or override inherited styles when needed. By the end, inheritance will feel like a tool you intentionally use — not a side effect you stumble into.</p>
<h2>What Is CSS Inheritance?</h2>
<p>Inheritance is the mechanism by which some CSS property values applied to a parent element are passed down to its child elements.</p>
<p>In simple terms:</p>
<blockquote>
<p>If a parent element has a certain style, its children may automatically receive that style — unless they explicitly override it.</p>
</blockquote>
<p>This behavior helps avoid repeating the same declarations across many elements.</p>
<pre><code class="language-css">body {
font-family: Arial, sans-serif;
color: #333;
}
</code></pre>
<p>All text inside the <code>body</code> element inherits these values unless otherwise specified.</p>
<h2>Properties That Inherit by Default</h2>
<p>Not all CSS properties inherit. In general, <strong>text-related properties</strong> do.</p>
<p>Common inheriting properties include:</p>
<ul>
<li><code>color</code></li>
<li><code>font-family</code></li>
<li><code>font-size</code></li>
<li><code>font-style</code></li>
<li><code>font-weight</code></li>
<li><code>line-height</code></li>
<li><code>visibility</code></li>
</ul>
<p>This makes sense — text inside a paragraph should usually look like the text around it.</p>
<h2>Properties That Do Not Inherit</h2>
<p>Layout and box-model properties typically do <strong>not</strong> inherit.</p>
<p>Examples include:</p>
<ul>
<li><code>margin</code></li>
<li><code>padding</code></li>
<li><code>border</code></li>
<li><code>width</code> / <code>height</code></li>
<li><code>background</code></li>
<li><code>display</code></li>
</ul>
<pre><code class="language-css">div {
padding: 20px;
}
</code></pre>
<p>Child elements do <strong>not</strong> inherit padding — each element controls its own box.</p>
<h2>Inheritance vs the Cascade</h2>
<p>Inheritance is not the same as the cascade.</p>
<ul>
<li><strong>Inheritance</strong> passes values from parent to child</li>
<li><strong>The cascade</strong> resolves conflicts between competing rules</li>
</ul>
<p>If a child element has its own declared value, it overrides any inherited value — regardless of specificity.</p>
<pre><code class="language-css">p {
color: blue;
}
span {
color: red;
}
</code></pre>
<p>The <code>span</code> will be red, even if it’s inside a blue paragraph.</p>
<h2>Forcing Inheritance with <code>inherit</code></h2>
<p>You can explicitly tell a property to inherit its value from its parent.</p>
<pre><code class="language-css">button {
color: inherit;
font-family: inherit;
}
</code></pre>
<p>This is useful for elements like buttons and inputs, which do not inherit text styles by default.</p>
<h2>Resetting Inheritance with <code>initial</code> and <code>unset</code></h2>
<p>CSS provides keywords to control inheritance precisely.</p>
<h3><code>initial</code></h3>
<p>Resets a property to its default browser value.</p>
<pre><code class="language-css">p {
color: initial;
}
</code></pre>
<h3><code>unset</code></h3>
<p>Acts as:</p>
<ul>
<li><code>inherit</code> for inheriting properties</li>
<li><code>initial</code> for non-inheriting properties</li>
</ul>
<pre><code class="language-css">p {
color: unset;
}
</code></pre>
<h2>Inheritance in Component-Based Systems</h2>
<p>In modern component-based architectures, inheritance can be both helpful and dangerous.</p>
<p>Good use cases:</p>
<ul>
<li>Setting base typography on a container</li>
<li>Applying theme colors</li>
</ul>
<p>Potential pitfalls:</p>
<ul>
<li>Unintended style leakage</li>
<li>Hidden dependencies between components</li>
</ul>
<p>The key is to be intentional about where inheritance starts and stops.</p>
<h2>Mental Model: Inheritance as Defaults</h2>
<p>Think of inheritance as <strong>default behavior</strong>, not enforcement.</p>
<ul>
<li>Parents suggest styles</li>
<li>Children may accept or override them</li>
<li>Explicit declarations always win</li>
</ul>
<p>Used well, inheritance reduces repetition and improves consistency.</p>
<h2>Final Thoughts</h2>
<p>CSS inheritance is one of the reasons stylesheets can stay small and expressive — but only when you understand it clearly. Knowing which properties inherit, how to control them, and when to break the chain gives you confidence and precision in your styling decisions.</p>
<p>Rather than fighting inheritance, embrace it as a design tool. When combined thoughtfully with specificity and the cascade, it becomes a powerful ally in writing clean, maintainable CSS.</p>
<p>Happy coding — and may your styles flow exactly where you expect them to ✨</p>]]></content:encoded>
</item>
<item>
<title><![CDATA[Deep Dive in Advanced React Patterns]]></title>
<link>http://irenaapp.de//blog-advanced-react-overview/</link>
<guid>http://irenaapp.de//blog-advanced-react-overview/</guid>
<pubDate>Wed, 23 Nov 2022 14:37:00 GMT</pubDate>
<description><![CDATA[React has revolutionized the way we build user interfaces, making component-based architecture the standard for modern web development. But…]]></description>
<content:encoded><![CDATA[<p>React has revolutionized the way we build user interfaces, making component-based architecture the standard for modern web development. But as applications grow, simple props and local state aren’t always enough. Complex apps demand scalable state management, efficient rendering, and maintainable component structures. That’s where advanced React patterns come into play.
At its core, React makes data flow predictable with unidirectional props, while state and context allow dynamic updates across components. But as your application grows, the simple patterns that work for small apps—passing props, managing local state—can quickly become cumbersome, difficult to maintain, or inefficient.
This is where advanced React patterns become essential. They help developers structure their applications in a way that is scalable, maintainable, and performant, even as complexity increases. These patterns aren’t just about making code work—they’re about making it work smart. By combining Context for global state management, useReducer for complex state logic, memoization with useMemo and useCallback, and lazy loading with React.lazy, developers can build apps that are responsive, modular, and optimized for performance.</p>
<p>In this deep dive, we’ll go beyond simple examples and explore real-world solutions to common challenges: avoiding prop drilling, managing shared state across large component trees, preventing unnecessary re-renders, and designing reusable, composable components. We’ll examine patterns and techniques used by professional developers to keep codebases clean, readable, and easy to extend.</p>
<p>In this post, we’re going beyond the basics. We’ll explore powerful patterns for state management, component composition, and performance optimization that allow developers to build apps that are not only functional but also robust and future-proof. From useReducer and Context to memoization, lazy loading, and reusable component strategies, you’ll discover techniques that professional React developers use to tackle real-world challenges.</p>
<p>By the end, you’ll have a toolkit of strategies to write cleaner, faster, and more maintainable React applications, and you’ll understand how modern React patterns can turn a sprawling codebase into a well-organized, scalable system.</p>]]></content:encoded>
</item>
<item>
<title><![CDATA[CSS positioning Properties 🤔]]></title>
<link>http://irenaapp.de//blog-css-positioning-properties/</link>
<guid>http://irenaapp.de//blog-css-positioning-properties/</guid>
<pubDate>Sat, 10 Sep 2022 23:16:21 GMT</pubDate>
<description><![CDATA[What You See Is What You Get – is a competing model for authoring documents. These
applications constantly update a final form presentation…]]></description>
<content:encoded><![CDATA[<p>What You See Is What You Get – is a competing model for authoring documents. These
applications constantly update a final form presentation. As the author types, the screen is updated to reflect the page layout that would result should the document be printed at that point.
A successful style sheet language for the web had to be compelling enough both for browser developers to implement, and for authors to use.</p>
<blockquote>
<p>Style sheet languages and structured document formats are mutually dependent on each other. Without style sheets, structured documents cannot be presented, and without structured documents there is nothing for style sheets to present. Due to the strong relationship between the two, it is important to understand structured documents when studying style sheet languages.</p>
</blockquote>
<p>One of the most attractive features of structured documents is that the content can be used in many contexts and presented in various ways. A variety of different stylesheets can be attached to the logical structure to serve different needs. However, theflexibility that structured documents offer comes at a price since some kind of stylesheet mechanism is needed to make the content available for users.</p>
<p>Elements of a website’s user interface (UI) can interact with and overlay on top of one another in many different ways, making CSS layout challenging to control. One way to set the placement of an element and how it overlays other elements is with a combination of the position property, z-index property, and the direction properties, which apply spacing values with top, right, bottom, and left. Experience with these CSS properties will enable you to create UI elements like dropdown navigation bars and figure captions efficiently and quickly.</p>
<h2>The position CSS property</h2>
<p>The position property tells the browser how an element should be positioned on the page. By default the value of position is static, but we can modify it to be any of the following values: relative, absolute, fixed, sticky. In this post I will go over each of them.
The CSS position property is used to set position for an element. it is also used to place an element behind another and also useful for scripted animation effect.</p>
<p>You can position an element using the top, bottom, left and right properties. These properties can be used only after position property is set first. A position element's computed position property is relative, absolute, fixed or sticky.</p>
<p>We will use a simple HTML markup which is really simple for better understanding. It contains a container div, and 3 child divs, that we will position throughout the examples.
I also added different colors to these child divs, so it will be easier to see the difference.</p>
<pre><code class="language-html"><!DOCTYPE html>
<html lang="en">
<head>
<link rel="stylesheet" href="./styles.css" />
<title>CSS positions</title>
<style>
.container {
background-color: blue;
padding: 20px;
}
.container > div {
padding: 15px;
}
.container span {
margin-bottom: 20px;
}
.first {
background-color: green;
}
.second {
background-color: red;
}
.third {
background-color: lightyellow;
}
</style>
</head>
<body>
<div class="container">
<span>Container</span>
<div class="first">First</div>
<div class="second">Second</div>
<div class="third">Third</div>
</div>
</body>
</html>
</code></pre>
<p>Let's have a look at following CSS positioning:</p>
<pre><code>👉 Static Positioning
👉 Fixed Positioning
👉 Relative Positioning
👉 Absolute Positioning
</code></pre>
<h2>Static</h2>
<p>This is the default value of the position property. If the position of an element is static, the element will render in order, based on the position of it in the original document flow.</p>
<h2>Relative</h2>
<p>If we set the position of an element to relative, it will appear in the document as it would by default using static. The trick is that by setting position relative, we gain access to the following CSS properties: top, left, right, bottom. With these we can add an offset to the specific direction. So for example if we set left: 20px. The element will be placed 20 pixel to the right. If we would have provided -20px it would push the content to the left with 20px.</p>
<p>Make the following changes:</p>
<pre><code class="language-css">.second {
background-color red;
position: relative;
left: 20px;
}
</code></pre>
<p>🛑 If you set position: relative on an element, you are now able to position it with an offset, using the properties</p>
<pre><code>top
right
bottom
left
</code></pre>
<p>which are called offset properties. They accept a length value or a percentage.
Let's have a look at the example bellow which is a parent container, a child container, and an inner box with some text:</p>
<pre><code class="language-html"><div class="parent">
<div class="child">
<div class="box">
<p>Test</p>
</div>
</div>
</div>
</code></pre>
<p>CSS to give some colors and padding, but does not affect positioning:</p>
<pre><code class="language-css">.parent {
background-color: #af47ff;
padding: 30px;
width: 300px;
}
.child {
background-color: #ff4797;
padding: 30px;
}
.box {
background-color: #f3ff47;
padding: 30px;
border: 2px dotted #333;
font-family: courier;
text-align: center;
font-size: 2rem;
}
</code></pre>
<p>here’s the result:</p>
<p>You can play around and try to add any of the properties that I mentioned before (top, right, bottom, left) to <code>.box</code>, and `you will see that nothing will happen. The position is static.</p>
<p>But if we set position: <code>relative</code> to the box, at first apparently nothing changes. But the element is now able to move using the top, right, bottom, left properties, and now you can alter the position of it relatively to the element containing it.</p>
<p>For example:</p>
<pre><code class="language-css">.box {
/* ... */
position: relative;
top: -60px;
}
</code></pre>
<h2>Fixed</h2>
<p>With fixed positioning we also have access to top, left, right, bottom properties. In this case the element is positioned relative to the browser window's viewport.</p>
<p>So if we set top 70px and left 20px on a fixed positioned element it will appear 70 pixels from the top of the viewport and 20px from the left edge of the viewport. Fixed positioning also removes the document from the normal document flow.</p>
<p>Modify the CSS:</p>
<pre><code class="language-css">.second {
background-color: red;
position: fixed;
left: 20px;
top: 70px;
}
</code></pre>
<p>Like with absolute positioning, when an element is assigned <code>position: fixed</code> it’s removed from the flow of the page.</p>
<p>The difference with absolute positioning is this: elements are now always positioned relative to the window, instead of the first non-static container.</p>
<pre><code class="language-css">
.box {
/* ... */
position: fixed;
}
</code></pre>
<pre><code class="language-css">
.box {
/* ... */
position: fixed;
top: 0;
left: 0;
}
</code></pre>
<h2>Absolute</h2>
<p>Absolute positioning is the one which can trick developers. It is working like the fixed positioning, but it is not positioned relatively to the viewport, but instead it is positioned based on the closest positioned element (which has position other than static). If there are no positioned parents it will be positioned relative to the viewport (Same result as it would be with fixed).</p>
<p>Make these changes to the CSS:</p>
<pre><code class="language-css">.second {
background-color: red;
position: absolute;
left: 20px;
top: 70px;
}
</code></pre>
<p>If we add a position value to a parent, in this case we will add it to the container div, the absolutely positioned child will be positioned relatively to that. We often use relative position for the parent as it won't remove it from the standard document flow, and the parent will be placed in the site where it would have been without position: relative.</p>
<p>Add position relative to the container:</p>
<pre><code class="language-css">.container {
background-color: blue;
padding: 20px;
position: relative;
}
</code></pre>
<h2>Sticky</h2>
<p>Using sticky will position our element based on the user's scroll position. It toggles between position relative and fixed. We can provide the offsets using top, left, right, bottom. Until the specified offsets are met the element acts like a relatively psoitioned element, but when the scroll position is greater than the offset it "swithces" to position fixed and be positioned relatively to the viewport. It stays fixed until the user scrolls back to the opposite direction and the distance will be less than the offset, then it goes back to act like a relative positioned element again.</p>
<p>To be able to scroll add 3 times the height of the viewport to our container:</p>
<pre><code class="language-css">.container {
background-color: blue;
padding: 20px;
height: 300vh;
}
</code></pre>
<p>Add the sticky position and the top offset to the element:</p>
<pre><code class="language-css">.second {
background-color: red;
position: sticky;
top: 0;
}
</code></pre>
<h2>Z-Index</h2>
<p>The Z-Index property is used to specify the stacking order of the elements that overlap. The stack level refers to the element’s position on the Z-axis.
👉 Elements with a higher z-index value are displayed in front of those with a lower z-index value.</p>
<p>Default stacking order</p>
<p>Let’s first mention the default order the browser stacks elements in, when no z-index is applied:</p>
<blockquote>
<p>Root element (the <html> element)</p>
</blockquote>
<blockquote>
<p>Non-positioned elements in the order they are defined</p>
</blockquote>
<blockquote>
<p>Positioned elements in the order they are defined</p>
</blockquote>
<p>A non-positioned element is an element with the default position value static. A positioned element is an element with any other position value. Examples of other values are: absolute, relative, sticky or fixed.</p>
<pre><code class="language-html"><div class=”pink”>
<div class=”orange”></div>
</div>
<div class=”blue”></div>
<div class=”green”></div>
</code></pre>
<pre><code class="language-css">.blue, .pink, .orange {
position: absolute;
}
</code></pre>
<p>We defined the green box last in the document. Still, it appears behind the others because it is non-positioned.
Stacking with z-index</p>
<p>If we now want to change the stacking order of these elements, we can use the property z-index. An element with a higher z-index will be displayed in front of an element with a lower z-index. One thing to note is that z-index only works with positioned elements.</p>
<pre><code class="language-css">
.blue, .pink, .orange {
position: absolute;
}
.blue {
z-index: 2;
}
.orange {
z-index: 3;
}
.green {
z-index: 100; // it has no effect since the green box is non-positioned
}
</code></pre>
<p>The orange box with a higher z-index is displayed in front of the blue box.</p>
<p>By using <code>z-index</code> on positioned elements, we can change the default stacking order.
When applying certain CSS properties, an element can form a stacking context. Z-index values only have a meaning within the same stacking context.</p>
<h2>Stacking Context</h2>
<p>Let’s say that we add another positioned box to the layout which we want to position behind the pink box. We update our code to the following:</p>
<pre><code class="language-html"><div class=”pink”>
<div class=”orange”></div>
</div>
<div class=”blue”></div>
<div class=”purple”></div>
<div class=”green”></div>
</code></pre>
<pre><code class="language-css">.blue, .pink, .orange, .purple {
position: absolute;
}
.purple {
z-index: 0;
}
.pink {
z-index: 1;
}
.blue {
z-index: 2;
}
.orange {
z-index: 3;
}
.green {
z-index: 100;
}
</code></pre>
<p>The pink box is displayed in front of the purple box as expected, but what happened to the orange box? Why is it all of a sudden behind the blue one even though it has a higher z-index? This is because adding a z-index value to an element forms what is called a stacking context.</p>
<blockquote>
<p>The pink box has a z-index value other than auto, which forms a new stacking context. The fact that it forms a stacking context affects how its child elements are being displayed.</p>
</blockquote>
<p>It is possible to change the stacking order of the pink box child elements. However, their z-index only has a meaning within that stacking context. This means that, we won’t be able to move the orange box in front of the blue box, because they are not within the same stacking context anymore.</p>
<p>If you want the blue box and the orange box to be part of the same stacking context, we can define the blue box as a child element of the pink box. This will make the blue box appear behind the orange one.</p>
<pre><code class="language-html"><div class=”pink”>
<div class=”orange”></div>
<div class=”blue”></div>
</div>
<div class=”purple”></div>
<div class=”green”></div>
</code></pre>
<p>Stacking contexts are not only formed when applying z-index to an element. There are several other properties that cause elements to form stacking contexts. Some examples are: filter, opacity, and transform.</p>
<p>let's apply a filter to the box</p>
<pre><code class="language-html"><div class=”pink”>
<div class=”orange”></div>
</div>
<div class=”blue”></div>
<div class=”green”></div>
</code></pre>
<pre><code class="language-css">.blue, .pink, .orange {
position: absolute;
}
.pink {
filter: hue-rotate(20deg);
}
.blue {
z-index: 2;
}
.orange {
z-index: 3;
}
.green {
z-index: 100;
}
</code></pre>
<p>The orange box still has a higher z-index than the blue one, but is still displayed behind it. This is because the filter value caused the pink box to form a new stacking context.
🛑
About z-index: 0 it's important to note the following:</p>
<p><code>z-index: 0 </code>creates a stacking context while <code>z-index: auto</code> do not
In most cases this won't affect the rendered elements.</p>
<p>🛑 Note: z-index only works on positioned elements (position: absolute, position: relative, position: fixed, or position: sticky) and flex items (elements that are direct children of display:flex elements).</p>
<p>🛑 Note: If two positioned elements overlap without a z-index specified, the element positioned last in the HTML code will be shown on top.</p>
<p>Simply in CSS, you can position 2 or more objects to overlap each other. Their <code>z-indexes</code> determine which objects are "in front of" or "behind" other objects that they overlap. The higher an object's z-index, the "higher in the stack" of objects it will display.</p>
<blockquote>
<p><code>z-index:0</code> is always the "default layer" (the layer in which all elements without an explicit z-index reside), and z-index:auto means: "Sets the stack order equal to its parent". Since all the children of a parent by default start in the "z-layer 0" - relative to their parent, then, in-affect, z-index:auto and <code>z-index:0</code>means the same thing: they will both be in the same "layer", and their stacking order will be according to the default stacking rules`</p>
</blockquote>
<p><a href="https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Positioning/Understanding_z_index/Stacking_and_float">Stacking with floated blocks</a></p>
<pre><code class="language-html"><div id="example-auto">
<div class="box red">
<div class="box green" style="z-index: 1"></div>
</div>
<div class="box blue"></div>
</div>
<div id="example-0">
<div class="box red" style="z-index: 0">
<div class="box green" style="z-index: 1"></div>
</div>
<div class="box blue"></div>
</div>
</code></pre>
<pre><code class="language-css">
.box {
position: relative;
width: 64px;
height: 64px;
top: 32px;
left: 32px;
}
.red {
background: red;
}
.green {
background: green;
}
.blue {
background: blue;
}
#example-0 {
margin-top: 32px;
}
</code></pre>
<p>In both examples, red and blue are siblings with a position: relative and green is a child of red with position: relative and z-index: 1:</p>
<pre><code>Root
Red: position: relative
Green: position: relative; z-index: 1
Blue: position: relative
</code></pre>
<p>In the first example, green will be positioned above red and blue. This is because it has a z-index: 1, so a stacking context is created and put above the root context.</p>
<p>In the second example, green will be positioned above red, but below blue. This is because red has z-index: 0, so it creates a stacking context at the same level of blue. So green will be above red (because green also creates a stacking context), but below blue because it's trapped in the context of red.</p>
<p><a href="https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Positioning/Understanding_z_index/The_stacking_context">The stacking context</a></p>
<p>If you have any questions regarding the CSS Positioning lesson, let me know in the comments section. I will get back to you as soon as possible.</p>
<p>Happy learning! 💻</p>]]></content:encoded>
</item>
<item>
<title><![CDATA[Unraveling the mystery of percentage-based heights in CSS]]></title>
<link>http://irenaapp.de//blog-the-height-enigma/</link>
<guid>http://irenaapp.de//blog-the-height-enigma/</guid>
<pubDate>Sat, 20 Aug 2022 14:37:00 GMT</pubDate>
<description><![CDATA[Today, my thoughts were wandering through the curious world of CSS heights, and I found myself fascinated by one of front-end development’s…]]></description>
<content:encoded><![CDATA[<p>Today, my thoughts were wandering through the curious world of CSS heights, and I found myself fascinated by one of front-end development’s subtle mysteries: why something as seemingly simple as height: 100% can behave so unpredictably. At first glance, setting a percentage height seems straightforward—after all, percentages work perfectly for widths—yet in practice, height percentages are deeply dependent on the heights of parent elements. Without a defined reference, child elements collapse, layouts break, and developers are left scratching their heads. As I explored this behavior further, it became clear that understanding how browsers calculate percentage heights is essential for building reliable, responsive layouts. In this article, we’ll take a deep dive into these mechanics, examine common pitfalls, and explore practical strategies—including Flexbox, CSS Grid, and viewport units—to ensure your layouts behave consistently. Whether you’re working on full-page hero sections, nested components, or dynamic responsive interfaces, mastering percentage-based heights is a small detail with a big impact on usability and visual consistency</p>
<p>At first glance, setting an element’s height in CSS seems simple, just define a percentage, right? But if you’ve ever tried to make a div fill its parent using height: 100% and watched it collapse instead, you know that percentage-based heights in CSS can be surprisingly tricky. Unlike widths, which usually calculate intuitively relative to the parent’s content box, height percentages are dependent on the parent’s explicitly defined height, and if that reference is missing, the result is often auto—leading to unexpected layouts and frustrating bugs.</p>
<p>This challenge becomes even more pronounced in complex web layouts, where multiple nested containers, dynamic content, or responsive designs are involved. Developers frequently run into situations where a child element doesn’t stretch as expected, or layout shifts occur when the viewport changes, making the behavior of percentage-based heights one of the most misunderstood aspects of CSS.</p>
<p>In this lesson we’ll take a deep dive into the mechanics of CSS percentage heights, exploring:</p>
<ul>
<li>
<p>How browsers calculate percentage heights relative to parent elements</p>
</li>
<li>
<p>Common pitfalls like collapsed children and zero-height containers</p>
</li>
<li>
<p>Practical solutions using Flexbox, CSS Grid, and viewport units</p>
</li>
<li>
<p>Strategies for building robust, responsive layouts that behave predictably across devices</p>
</li>
</ul>
<p>By the end of this guide, you’ll not only understand why percentage heights sometimes fail but also have a toolkit of strategies to control and manipulate heights reliably, whether you’re building a full-page hero section, a responsive card layout, or nested components in modern web applications.</p>
<p>CSS percentages can be tricky, especially when dealing with <strong>height</strong>. Unlike width, which is straightforward—percentage widths are relative to the parent element—<strong>percentage-based heights often leave developers scratching their heads</strong>. You may have set <code>height: 100%</code> on a child element, only to find it collapses or doesn’t behave as expected.</p>
<p>Understanding <strong>how percentage heights are calculated</strong> is key to building flexible, responsive layouts. In this article, we’ll explore how CSS calculates percentage heights, common pitfalls, and practical strategies to make percentage-based heights work reliably in your designs.</p>
<h2>1. How CSS Calculates Percentage Heights</h2>
<p>In CSS, a percentage height is calculated <strong>relative to the height of the parent element</strong>. However, if the parent element doesn’t have an explicit height, the child’s percentage height won’t have a reference and will collapse to <code>auto</code>.</p>
<pre><code class="language-css">.parent {
height: 300px;
background-color: lightblue;
}
.child {
height: 50%;
background-color: coral;
}
</code></pre>
<p>In this example, .child will have a height of 150px, exactly 50% of the parent. But if .parent didn’t have a defined height, .child’s 50% would not render as expected.</p>
<h2>2. The Auto-Height Trap</h2>
<p>Many developers expect height: 100% to fill the page automatically, but it only works if all parent elements up to <html> and <body> have defined heights.</p>
<pre><code class="language-css">html, body {
height: 100%;
}
.container {
height: 100%;
}
.inner {
height: 100%;
background-color: coral;
}
</code></pre>
<p>Without defining html and body heights, .inner will not stretch fully.</p>
<h2>3. Using Flexbox for Reliable Heights</h2>
<p>Flexbox can make handling percentage heights more predictable. Setting a parent to display: flex and a child to flex: 1 lets the child grow to fill the available space without manually calculating percentages:</p>
<pre><code class="language-css">.parent {
display: flex;
flex-direction: column;
height: 400px;
background-color: lightblue;
}
.child {
flex: 1;
background-color: coral;
}
</code></pre>
<p>The child now fills the remaining height reliably, even when the parent’s height changes dynamically.</p>
<h2>4. Using Viewport Units as an Alternative</h2>
<p>When you want an element to scale relative to the browser window rather than its parent, vh (viewport height) is often easier than percentage heights:</p>
<pre><code class="language-css">.hero {
height: 100vh; /* fills the entire viewport height */
background-color: tomato;
}
</code></pre>
<p>1vh equals 1% of the viewport height, providing predictable results for full-page layouts.</p>
<h2>5. Practical Tips</h2>
<ul>
<li>
<p>Always define the height of parent elements if using percentage-based heights.</p>
</li>
<li>
<p>Combine flexbox or grid for dynamic, responsive layouts.</p>
</li>
<li>
<p>Consider viewport units (vh) for full-page sections.</p>
</li>
</ul>
<p>Test across multiple screen sizes—percentage heights can behave differently depending on parent structure and content.</p>
<p>Percentage-based heights in CSS can feel like a mystery at first, but the behavior becomes predictable once you understand the rules: percentages depend on parent heights, and without a reference, they collapse. Using strategies like explicit parent heights, flexbox, and viewport units ensures your layouts behave consistently.</p>
<p>Percentage-based heights in CSS can be deceptively tricky. Unlike widths, which are generally straightforward, percentage heights depend entirely on the parent element’s height, and without a defined reference, they often collapse to auto. Understanding this fundamental behavior is key to building predictable, responsive layouts. Throughout this article, we explored why children elements sometimes fail to expand, the importance of explicitly setting heights on parent containers, and the chain of dependencies that affect nested elements.</p>
<p>We also examined practical solutions for real-world layouts. Flexbox allows elements to grow and fill available space without relying on exact percentages, while CSS Grid offers additional control over rows and columns. For full-page sections, viewport units (vh) provide a reliable way to size elements relative to the window, bypassing parent constraints entirely. Combined, these tools give developers multiple approaches to solve layout challenges effectively.</p>
<p>Finally, we highlighted best practices for building maintainable and robust layouts: always define parent heights when using percentages, use flex or grid for dynamic layouts, and test across multiple devices and viewport sizes. By mastering these techniques, you can eliminate unexpected behavior, maintain consistent designs, and create responsive, professional-grade interfaces.</p>
<p>Percentage heights may seem like a small detail, but in practice, they can have a big impact on the structure and usability of your layouts. With a deep understanding of how CSS calculates heights and the strategies discussed here, you now have the knowledge to confidently design flexible, reliable, and visually consistent web interfaces.</p>
<p>Mastering these techniques allows you to build responsive, dynamic, and visually consistent layouts, avoiding common pitfalls and ensuring your elements always occupy the intended space. Once you grasp this concept, percentage heights become a powerful tool in your CSS toolkit, giving you flexibility without compromising layout integrity.</p>
<p>Happy coding!</p>]]></content:encoded>
</item>
<item>
<title><![CDATA[Different React Props Patterns🤖]]></title>
<link>http://irenaapp.de//blog-react-patterns/</link>
<guid>http://irenaapp.de//blog-react-patterns/</guid>
<pubDate>Tue, 12 Oct 2021 23:15:21 GMT</pubDate>
<description><![CDATA[Different React Props patterns and how to manage Data Understanding React’s approach to data manipulation takes time. React has a different…]]></description>
<content:encoded><![CDATA[<h2>Different React Props patterns and how to manage Data</h2>
<p>Understanding React’s approach to data manipulation takes time. React has a different approach to data flow & manipulation than other frameworks, and that’s why it can be difficult at the beginning to understand some concepts like props, state, and so on.</p>
<p>To start using React you actually need to master a few important concepts. React's Props feature is one of them. Learn the concept of components, state, props, and hooks — and you know how to use React.</p>
<p>Here, briefly in my article I will summerise how props can be used on React component.</p>
<p>What is important to bear in mind is that in order to understand how props work, you need to have a general understanding of the concept of components.</p>
<p>When I started learning React, I was curious about what are props and how they actually work.</p>
<p>👉 Props stand for properties and is a special keyword in React</p>
<p>👉 Props are being passed to components like function arguments</p>
<p>👉 Props can only be passed to components in one way (parent to child)</p>
<p>👉 Props data is immutable (read-only)</p>
<blockquote>
<p>🛑 In JavaScript, we can access object elements with dot(.) notation.</p>
<p>🛑 In react we can render a property with an interpolation</p>
</blockquote>
<pre><code class="language-js">const ChildComponent = (props) => {
return <p>{props.text}</p>;
};
</code></pre>
<p>🤖 React is a <code>component-based</code> library that divides the UI into little reusable pieces. In some cases, those components need to communicate (send data to each other) and the way to pass data between components is by using props.
“Props” is a special keyword in React, which stands for properties and is being used for passing data from one component to another.
But the important part here is that data with props are being passed in a uni-directional flow. (one way from parent to child)
Furthermore, props data is read-only, which means that data coming from the parent should not be changed by child components.</p>
<h2>🚀 React props can be passed conditionally</h2>
<p>Props that are passed to components can be thought of like arguments that are passed to a function.</p>
<p>If prop values are not passed a certain component, an error will not be thrown. Instead, within the component that prop will have a value of undefined.</p>
<pre><code class="language-js">export default function App(){
return (
<MyComponent title"My React basics!"/>
);
}
function MyComponent(props) {
return (
<h1>My React basics{props.tittle}!</h1
)
}
</code></pre>
<p>So Props in react can be used in the following ways:</p>
<p>👉 Firstly, define an attribute and its value(data)</p>
<p>👉 Then pass it to child component(s) by using Props</p>
<p>👉 Finally, render the Props Data</p>
<p>If you would like to be alerted to when a value is not passed as a prop to a component, you can use a tool like prop-types or TypeScript using these tools.</p>
<h2>🤔 React props passed with just their name have a value of <code>true</code></h2>
<p>Every prop must be given an associated value that is provided after the equals operator.</p>
<p>But what happens when we don't provide that equals operator as well as a value?</p>
<p>If you just provide the proper name on a component with nothing else, you pass a boolean value of true for that prop to the component. There is no need to write that a prop is equal to true.</p>
<p>Instead, you can just include the prop value, and it will be given the boolean value true when you use it in a component to which you pass it.</p>
<pre><code class="language-js">export default function App(){
return (
<MyComponent showTitle={true} />
);
function MyComponent(props) {
if (props.showTitle) {
return <h1>My React basics<h1/>
}
return null;
</code></pre>
<h2>React props can be accessed as an object or destructured</h2>
<p>There are a couple of patterns we can use for accessing prop values in our components.</p>
<p><code>Props</code> can be accessed as an <code>entire object</code> which is usually called <code>"props"</code>. Or they can be destructured, since props will always be an object, into separate variables.</p>
<p>If you have a lot of props that you're passing down to your component, it may be best to include them on the entire props object and access them by using <code>props.propName</code>.</p>
<p>However, if you only have a few props that you're passing down to your component, you can immediately destructure them within the parameters of your function component.</p>
<pre><code class="language-js">export default function App(){
return (
<MyComponent showTitle title="My react basics" />
);
}
function MyComponent(props) {
if (props.showTitle) {
return <h1>{title}<h1/>
}
return null;
}
</code></pre>
<p>Actually ES6 object destructuring can be used to include a set of curly braces within the function component's parameters, and immediately grab the properties off of the object, as well as declare them as separate variables.</p>
<p>This cuts down the code and eliminates the need to use <code>props.propName</code> to get each props value.</p>
<h2>React components can be passed as props (including children)</h2>
<p>👉 The props are very flexible, and if we don't pass them to a component, an error will not be thrown.</p>
<p>This flexibility is also extended to what we can pass as a prop. Not only can JSX elements be passed as props to components, but we can also pass other components as props.</p>
<p>In fact, there is a special type of prop that is automatically provided on the props object called <code>children</code>.</p>
<blockquote>
<p>🛑 We receive any children for a given component if any components or elements are passed between the opening and closing tags of that component.</p>
</blockquote>
<pre><code class="language-js">
</code></pre>
<p>👉 The children prop allows us to compose our components in powerful ways.</p>
<p>This is especially helpful when we need to wrap one component around another, such as for styling, or to pass more component data to the children components to give two examples:</p>
<p><code>Children props</code> are very helpful when you want to make a <code>generic layout component</code> and give the same layout to all of the components that are passed as children.
Also, children are useful when you want to place a context provider from React context around your component tree to easily provide what is placed on context provider to all of its child components so they can receive the same data.</p>
<h2>Anything can be passed as a prop in React (especially functions)</h2>
<p>Any normal JavaScript value can be passed as props as well, including functions.</p>
<p>There are some powerful patterns which have emerged, due to the ability to pass functions as props. A very common pattern is passing a function down to a child component as a prop, which can update the parent component's state, and then calling it within that child component.</p>
<pre><code class="language-js">export default function App() {
const [title, setTitle] = React.useState('My React basics')
return(
<MyComponent title={title setTitle={setTitle}/>
);
}
function MyComponent({ title, setTitle }) {
function updateTitle(){
setTitle("My react basics")
}
return <h2 onClick={updateTitle}>{title}</>
}
</code></pre>
<p>Using this function that is passed down to update the parent's state and perform a function is called "lifting state up".
Additionally, there are other patterns, such as the render props pattern, which also involve passing a function down to a child component to then be called back and perform some cross-component function.</p>
<h2>Update a React prop's value with state</h2>
<p>🛑 Props cannot be directly updated.</p>
<p>To pass a prop value to a component, we cannot within that function component attempt to immediately change that prop's value.</p>
<blockquote>
<p>Prop values must be pure values. In other words, they cannot be mutated or changed directly.</p>
</blockquote>
<p>In React if we want to change values over time, the appropriate means to do so is with <code>state</code>.</p>
<pre><code class="language-js">
</code></pre>
<p>If we would like to pass in a prop value to a component and change it later on, we can give it to a stateful React hook to store that value as a variable. Then we can update it later on using the appropriate setter function. We can do so with the <code>useState</code> hook or the <code>useReducer</code> hook.</p>
<h2>React props can be spread in individually</h2>
<p>What if we have an object whose properties we want to pass down as individual prop values?</p>
<p>This object has a lot of properties, however. Do we need to manually create individual props and set the prop to object.propertyName?</p>
<p>No – instead of doing that for every property, we can very easily take the object and spread its properties down to a component as individual prop values using the object spread operator <code>{...myPropObject}</code>.</p>
<pre><code class="language-js">import React from 'react';
export default function App() {
const data = {
title:"my title",
description:"my description",
button: "learn more"
}
return (
<MyComponent{...data}/>
);
}
function MyComponent({title, description, button})
return(
<div>
<h1>{title}</h1>
<p>{description</p>
<button>{button}<button/>
</div>
)
}
return <h2 onClick={updateTitle}>{title}</>
}
</code></pre>
<p>When working with large objects with a lot of properties we want to pass as individual props to a component.</p>
<h2>React props can be given a default value if none is provided</h2>
<p>What if passing down a prop to one instance of a component, but do not passing that <code>prop</code> to another instance of it?</p>
<p>What to do to give a default value to a prop instead of just the value <code>undefined</code> if no prop value is passed to it?</p>
<p>🛑 If using destructuring to access that <code>prop</code> within the function component, the equals operator can be used to give it a default value. So if no prop value is passed for that prop, we can use the equals operator next to it and set it to a better default value.</p>
<p>Setting a default value is very important because the normal default value for a prop is undefined. This can help us avoid errors that may result from our expected prop value not being there.</p>
<h2>React props can be renamed to avoid errors</h2>
<p>What happens if there is a naming conflict with one of our props?</p>
<p>What if we use a prop name across many of the components and we see that there is another value within the component that has the same variable name?</p>
<p>Instead of having to go around and rename all of our prop values on all of our instances of our components, a colon after that prop name can be used, if we're destructuring it, to give it an alias. So to avoid naming conflict and errors give it a different name just in that instance.</p>
<h2>🛑 Don't attempt to destructure React props multiple times</h2>
<p>If we are destructuring an object from our props object, be aware that it is possible to destructure that prop even further into its constituent properties.</p>
<p>However, it is not generally recommended to do so unless being confident that that object will always have those properties.</p>
<p>If one of those properties is missing and you attempt to destructure it multiple levels deep, it can give an error when you're trying to access a property that doesn't exist.</p>
<h2>How to render the data coming from parent components?</h2>
<p>Each <code>ChildComponent</code> renders its own <code>prop data</code>. So in the snippet bellow is shown how <code>Props</code> can be used for passing data and converting static components into dynamic ones.</p>
<pre><code class="language-js">class ParentComponent extends Component {
render() {
return (
<h1>
The parent component.
<ChildComponent text={"the 1st child"} />
<ChildComponent text={"the 2nd child"} />
<ChildComponent text={"the 3rd child"} />
</h1>
);
}
}
</code></pre>
<p>Passing props is simple. Like we pass arguments to a function, we pass props into a React component and props bring all the necessary data.
Arguments passed to a function:</p>
<pre><code class="language-js">const addition = (firstNum, secondNum) => {
return firstNum + secondNum;
};
</code></pre>
<p>Arguments passed to a React component:</p>
<pre><code class="language-js">const ChildComponent = (props) => {
return <p>the 1st child!</p>;
};
</code></pre>
<blockquote>
<p>👉 <code>Props</code> actually are arguments passed into React components.</p>
</blockquote>
<p>Happy coding! 🌴 💻</p>]]></content:encoded>
</item>
<item>
<title><![CDATA[Rendering Lists of Data in React🤖]]></title>
<link>http://irenaapp.de//blog-react-rendering-lists-od-data/</link>
<guid>http://irenaapp.de//blog-react-rendering-lists-od-data/</guid>
<pubDate>Sat, 11 Sep 2021 23:16:21 GMT</pubDate>
<description><![CDATA[Rendering Lists of Data 🤔 How to show a simple list item, a list of objects, Nesting Lists in React, and lastly, we will have a look at how…]]></description>
<content:encoded><![CDATA[<h2>Rendering Lists of Data 🤔</h2>
<p>How to show a simple list item, a list of objects, Nesting Lists in React, and lastly, we will have a look at how to update the state of the React list.
Lists can be idiomatic and non-idiomatic.</p>
<p>👉 Idiomatic means following the conventions of the language. You want to find the easiest and most common ways of accomplishing a task rather than porting your knowledge from a different language.</p>
<blockquote>
<p>Idiomatic in the context of programming can usually be defined as "the most natural way to express something in a language"</p>
</blockquote>
<p>Note that just because a piece of code is idiomatic, does not mean that it is clean or even concise. Many times you must make compromises.</p>
<p>So basically, idiomatic most commonly refers to the most common way to write something in a language, often times including "slang" (idioms). If a piece of code is not idiomatic, it may be perfectly readable, concise, clean, and correct, but it may feel/look awkward in the language used. It is a preference of taste as to whether rewriting such a piece of code idiomatically would actually be a good thing and must be judged on a case by case basis.</p>
<p>The non-idiomatic ways aren't wrong, but they usually take longer to type and they always take longer to read, for those who know the idioms.</p>
<h2>The Non-React Way to Render a List</h2>
<p>If you’re not accustomed to functional programming yet, your first inclination to render a list might be to create a new array, then iterate over the list and push JSX elements into it.</p>
<p>Example:</p>
<pre><code class="language-js">function NonIdiomaticList(props) {
// Build an array of items
let array = [];
for(let i = 0; i < props.items.length; i++) {
array.push(
<Item key={i} item={props.items[i]} />
);
}
// Render it
return (
<div>
{array}
</div>
);
}
</code></pre>
<h2>The React Way to Render a List</h2>
<p>This component uses Array’s built-in map function to create a new array that has the same number of elements, and where each element is the result of calling the function you provide.</p>
<p>👉 To show the lists, we have to learn to use JavaScript’s <code>Array.map()</code> method. This method takes data transform to list view.</p>
<pre><code class="language-js">function ReactList(props) {
return (
<div>
{props.items.map((item, index) => (
<Item key={index} item={item} />
))}
</div>
);
}
</code></pre>
<h2>The <code>key</code> prop</h2>
<p>🛑 Remember!</p>
<blockquote>
<p>React relies on the <code>key</code> to identify items in the list. Remember React uses a virtual DOM, and it only redraws the components that changed since the last render.</p>
</blockquote>
<blockquote>
<p>The best choice for a key is an item’s unique ID, if it has one.</p>
</blockquote>
<p>The first time a component like IdiomaticReactList is rendered, React will see that you want to render a bunch of items, and it will create DOM nodes for them.</p>
<p>The next time that component renders, React will point out, “I have some list items on screen – are these ones different?” It will avoid recreating DOM nodes if it can tell that the items are the same.</p>
<p>But here’s the important trick: React can’t tell with a simple equality check, because every time a JSX element is created, that’s a brand new object, unequal to the old one.</p>
<p>So that’s where the <code>key</code> prop comes in. React can look at the <code>key</code> and know that even though this <Item> is not strictly <code>===</code> to the old <Item>, it actually is the same because the <code>keys</code> are the same.</p>
<p>This leads to a couple rules for keys. They must be:</p>
<p>👉 Unique – Every item in the list must have a unique key. So, <code>person.firstName</code> would not be a good choice, because it might not be unique).</p>
<p>👉 Permanent – An item’s key must not change between re-renders, unless that item is different. So, <code>Math.random</code> is a bad choice for a <code>key</code> because it will change every time and it might not be unique.
Back to the problem at hand: why isn’t an item’s array index always a good choice for a key? Even it seems to be unique and permanent 🤔</p>
<p>If you know for sure that the list of items is static, then the array index is a good choice.</p>
<p>If on the other hand, the items could be reordered at some point, that will cause weird rendering bugs. If the list can be sorted, or you might replace items with new items (like fetching a new list from the server), things may not render as expected. Think about what happens in those situations: a new item replaces the one at index <code>“0”</code>, but to React, that item is unchanged because it’s still called “0”, so it doesn’t re-render.</p>
<blockquote>
<p>if the list items have a unique id property of some sort, use that as a key.</p>
</blockquote>
<p>Another example</p>
<p>We have a array of Vagies, and we want to display the Fruits list in React app, so here is the code that we will use to render the list items using <code>.map()</code> method.</p>
<pre><code class="language-js">import React from 'react';
function App() {
const Vegies = [
{ name: 'Potato' },
{ name: 'Onion' },
{ name: 'Pepper' },
{ name: 'Aubergine' },
{ name: 'Pumpkin' },
{ name: 'Asparagus' },
{ name: 'Broccoli' },
{ name: 'Cabbage' }
];
return (
<div>
{Vegies.map(data => (
<p>{data.name}</p>
))}
</div>
);
}
export default App;
</code></pre>
<h2>Render a List in React with Key</h2>
<p>In the following React List example, we render a list of items that contain movie names and their respective id. We are using the <code>.map()</code> method to fetch the items from the Movies array, and every item has a unique key property.</p>
<p>🛑 Keys are used in React to figure out how to update a list, be it adding, updating, or deleting an item in a list.</p>
<p>Since React uses a virtual DOM and depends on the key to identifying items of a list, so in the above list example, we provided a unique id to every list item.</p>
<p>If we don’t define key prop to display a list in JSX, we might get error.</p>
<p>Remember:</p>
<blockquote>
<p>⚠️ Each child in a list should have a unique “key” prop.</p>
</blockquote>
<pre><code class="language-js">
import React from 'react';
function App() {
const Movies = [
{ id: 1, name: 'Meet Joe Black' },
{ id: 2, name: 'Eternals' },
{ id: 3, name: 'Troy' },
{ id: 4, name: 'Original sin' },
{ id: 5, name: 'The Holiday' },
{ id: 6, name: 'Salt' },
{ id: 7, name: 'Seven Years in Tibet' },
{ id: 8, name: 'The Tourist' }
];
return (
<ul>
{Movies.map(data => (
<li key={data.id}> {data.name}</li>
))}
</ul>
);
}
export default App;
</code></pre>
<h2>Display Object List in React</h2>
<p>Displaying items from a list of objects in React is very simple. We can iterate over a list of objects using the .map() method in React JSX. Here is the example in which we mapped a list of objects and displayed them in the React app.</p>
<pre><code class="language-js">import React from 'react';
function App() {
const Users = [
{
id: '01',
name: 'Jude Law',
email: 'jlaw@gmail.com',
phone: '222-235-0123'
},
{
id: '02',
name: 'Angelina Jolie',
email: 'fightclud@gmail.com',
phone: '101-535-0122'
},
];
return (
<ul>
{Users.map((data) => (
<li key={data.id}>
<p>{data.name}</p>
<p>{data.email}</p>
<p>{data.phone}</p>
</li>
))}
</ul>
);
}
export default App;
</code></pre>
<h2>React Nested Lists Example</h2>
<p>A combination of two arrays and point out the nested view using the list data in React.</p>
<pre><code class="language-js">
import React from 'react';
function App() {
const users = [
{
id: '01',
name: 'Jude Law',
email: 'jlaw@gmail.com',
phone: '222-235-0123'
},
{
id: '02',
name: 'Angelina Jolie',
email: 'fightclud@gmail.com',
phone: '101-535-0122'
},
];
const joinList = [users, users];
return (
<div>
<ul>
{joinList.map((nestedItem, i) => (
<ul key={i}>
<h3> List {i} </h3>
{nestedItem.map(data => (
<li key={data.id}>
<div>{data.id}</div>
<div>{data.name}</div>
<div>{data.email}</div>
<div>{data.phone}</div>
</li>
))}
</ul>
))}
</ul>
</div>
);
}
export default App;
</code></pre>
<p>Recap</p>
<p>to render a list in React follow the simple general rules:</p>
<blockquote>
<p>👉 use Array.map()</p>
<p>👉 Do not use a for loop</p>
<p>👉 Avoid using array index as key</p>
<p>👉 Give each item a unique key</p>
</blockquote>
<p>Happy Coding! 🌴 💻</p>]]></content:encoded>
</item>
<item>
<title><![CDATA[Vue Methods used for Data Binding 🤔]]></title>
<link>http://irenaapp.de//blog-vue-methods/</link>
<guid>http://irenaapp.de//blog-vue-methods/</guid>
<pubDate>Tue, 10 Aug 2021 23:16:21 GMT</pubDate>
<description><![CDATA[Methods in Vue used for data Binding What is Data binding? There are different Data Bindings in Vue. Data binding is a technique used to…]]></description>
<content:encoded><![CDATA[<h2>Methods in Vue used for data Binding</h2>
<h2>What is Data binding?</h2>
<p>There are different Data Bindings in Vue. Data binding is a technique used to bind data sources from the provider and consumer together and synchronize them at the time of retrieval. In a data binding process, whenever data is changed, it is reflected automatically by the elements bound to the data.</p>
<p>Its an easy to learn and approachable library. So, with the knowledge of HTML, CSS, and Javascript, we can build a web applications in Vue.js. Vue.js is built by combining the best features from an already existing Angular and React Frameworks.</p>
<p>🛑 Data binding is one of the most cool features of Vue.js because it provides reactive/two-way data binding. In Vue.js, we do not have to write a lot of lines to have <code>two-way data binding</code>, unlike other frameworks. One-way data binding means that the variable is just bound to the DOM. On the other hand, two-way means that the variable is also bound from the DOM. When DOM gets changed, the variable also gets changed. So, let’s take a look at both of the data bindings and see the right difference.</p>
<h2>One-way Data Binding</h2>
<p>If we want to bind any variable, we can simply use Vue.js’s double curly braces syntax or “Mustache” syntax to bind any variable from the relative component instance.</p>
<pre><code class="language-html">
<p> {{ dreamText }} </p>
</code></pre>
<p>if we want to bind any variable inside an HTML attribute, we can use the v-bind directive.</p>
<pre><code class="language-html"><div v-bind:class="container"></div>
</code></pre>
<p>Vue.js also provides the shorthand for binding variables in an HTML attribute. Instead of writing v-bind:attribute-name, we can only use a colon “:” and attribute name.</p>
<pre><code class="language-html"><div :class="container"></div>
</code></pre>
<p>But these are just data bindings. To demonstrate the two-way data binding, we can use the <code>v-model</code> directive provided by the Vue.js.</p>
<h2>Two-Way/Reactive Data Binding</h2>
<p>Reactive data binding, can be demonstrated using the <code>v-model</code> directive on an input form field. It will internally emit an event and change the variable. To which we can bind somewhere else in the template using Double curly braces or “Mustache” syntax.</p>
<pre><code class="language-html"><input v-model="dreamText" placeholder="Type something" />
<p>You are typing: {{ dreamText }}</p></td>
</code></pre>
<p>Now, whenever we enter a character in the input form field, we can see that the variable is also updating simultaneously.</p>
<p>Recap:</p>
<p>Binding variables in Vue.js can be done using double curly braces or the so called “Mustache” syntax.</p>
<p>Keep on learning the concepts of Vue.js with me. Thank you for visiting my space and study with me!</p>
<p>Happy Coding! 🌴 💻</p>]]></content:encoded>
</item>
<item>
<title><![CDATA[JavaScript Merge sort function 🤖]]></title>
<link>http://irenaapp.de//blog-merge-sort/</link>
<guid>http://irenaapp.de//blog-merge-sort/</guid>
<pubDate>Sun, 11 Apr 2021 23:14:21 GMT</pubDate>
<description><![CDATA[What is an algorithm? 🤔 An algorithm is a procedure for solving a problem in computer science. Some problems that algorithms are well…]]></description>
<content:encoded><![CDATA[<h2>What is an algorithm? 🤔</h2>
<p>An algorithm is a procedure for solving a problem in computer science. Some problems that algorithms are well-suited to solve include sorting a list, or finding the shortest path between two points. Other algorithms, like the minimax algorithm, allow computers to play adversarial games like tic-tac-toe or chess against human competitors in a strategic fashion. These are just a few examples of the kinds of problems algorithms can solve and form the basis for why algorithms in general are interesting.
I am trying to learn more about them and to challenge myself to understand and implement some classic algorithms using JavaScript. I think that working on these exercises will help me to reason more effectively about programming as well as improve my general competence as a web developer.</p>
<p>There is a subset of algorithmic approaches to problem-solving which are called “divide-and-conquer” type algorithms. With a “divide-and-conquer” algorithm one typically reduces the initial problem to several smaller sub-problems before applying an algorithm to each sub-problem and then recombining the smaller problems once they have been solved. Merge sort is one of them.</p>
<h2>What is a merge sort in JavaScript?</h2>
<p>Merge Sort is an important concept to understand when it comes to algorithms.
It is a sorting algorithm that uses the “divide and conquer” concept. Given an array, we first divide it in the middle and we get 2 arrays. We recursively perform this operation, until we get to arrays of 1 element. Then we start building up the sorted array from scratch, by ordering the individual items we got.</p>
<p>It works by recursively breaking down a problem into two or more sub-problems of the same or related type, until these become simple enough to be solved directly. The solutions to the sub-problems are then combined to give a solution to the original problem. So Merge Sort first divides the array into equal halves and then combines them in a sorted manner.</p>
<p>🛑 Remember: ⚠️ The concept of Divide and Conquer involves three steps:</p>
<p>👉 Divide the problem into multiple small problems.</p>
<p>👉 Conquer the sub-problems by solving them. The idea is to break down the problem into sub-problems, where they are actually solved.</p>
<p>👉 Combine the solutions of the sub-problems to find the solution of the actual problem.</p>
<h2>Merge Sort Algorithms: Steps on how it works:</h2>
<p>If it is only one element in the list it is already sorted, return.
Divide the list recursively into two halves until it can no more be divided.
Merge the smaller lists into new list in sorted order.</p>
<p>👇 Here is an example of writing the Merge Sort Algorithm</p>
<pre><code class="language-js">// Split the array into halves and merge them recursively
function mergeSort(array) {
if (array.length === 1) {
// Return once we hit an array with a single item
return array
}
// Get the middle item of the array rounded down by creating a variable
const middle = Math.floor(array.length / 2)
// Create a variable for the items on the left side
const left = array.slice(0, middle)
// Create a variable for the items on the right side
const right = array.slice(middle)
return merge(
mergeSort(left),
mergeSort(right)
)
}
// Compare the arrays item by item and return the concatenated result
function merge (left, right) {
let result = []
let indexLeft = 0
let indexRight = 0
while (indexLeft < left.length && indexRight < right.length) {
if (left[indexLeft] < right[indexRight]) {
result.push(left[indexLeft])
indexLeft++
} else {
result.push(right[indexRight])
indexRight++
}
}
return result.concat(left.slice(indexLeft)).concat(right.slice(indexRight))
}
const arrayOfNumbers = [2, 5, 1, 3, 7, 4, 2, 3, 9, 8, 6, 3]
console.log(mergeSort(arrayOfNumbers)) // [1, 2, 2, 3, 3, 3, 4, 5, 6, 7, 8, 9]
</code></pre>
<h2>🚀 Characteristics of Merge Sort:</h2>
<p>👉 Merge Sort is useful for sorting linked lists.</p>
<p>👉 Merge Sort is a stable sort which means that the same element in an array maintain their original positions with respect to each other.</p>
<p>👉 Overall time complexity of Merge sort is O(nLogn). It is more efficient as it is in worst case also the runtime is O(nlogn)</p>
<p>👉 The space complexity of Merge sort is O(n). This means that this algorithm takes a lot of space and may slower down operations for the last data sets.</p>
<h2>Let's recap with another example:</h2>
<p>Merge sort is an example of a divide-and-conquer type sorting-algorithm. The input for merge sort is an array of integers of length <code>n</code>, which needs to be sorted, typically from <strong><code>least</code></strong> to <strong><code>greatest</code></strong>. What merge sort does is it splits the unsorted array into two parts and then you recursively apply merge sort to these sub-arrays to further split the arrays until you are left with a bunch of single-element arrays. Then, you compare single-element arrays to one another before recombining them into a two-element, sorted array (and so on). If you do this repeatedly, eventually you end up with a single, sorted array of length n. Sorting algorithms are surprisingly complicated to grasp at first and I’m still trying to wrap my mind around the intricacies of computer sorting in general, but here is my attempt at implementing merge sort in JavaScript:</p>
<pre><code class="language-js">
let unsortedArr = [200, 1, 3, 3, 76, 26, 4, 12, 132, 8832, 646];
function merge(leftArr, rightArr) {
let sortedArr = [];
while (leftArr.length && rightArr.length) {
if (leftArr[0] <= rightArr[0]) {
sortedArr.push(leftArr[0]);
leftArr = leftArr.slice(1)
} else {
sortedArr.push(rightArr[0]);
rightArr = rightArr.slice(1)
}
}
while (leftArr.length)
sortedArr.push(leftArr.shift());
while (rightArr.length)
sortedArr.push(rightArr.shift());
return sortedArr;
}
function mergesort(arr) {
if (arr.length < 2) {
return arr; }
else {
let midpoint = parseInt(arr.length / 2);
let leftArr = arr.slice(0, midpoint);
let rightArr = arr.slice(midpoint, arr.length);
return merge(mergesort(leftArr), mergesort(rightArr));
}
}
console.log('Voala, the sorted array!')
console.log(mergesort(unsortedArr));
</code></pre>
<p>👉 You can test try the code in browser console to see the arbitrary arrays of integers,</p>
<h2>another merge example</h2>
<pre><code class="language-js">
function merge(arr1, arr2) {
let results = [];
let i = 0;
let j = 0;
while(i < arr1.length && j < arr2.length) {
if(arr2[j] > arr1[i]){
results.push(arr1[i]);
i++;
} else{
results.push(arr2[j])
j++;
}
}
while(i < arr1.length){
results.push(arr1[1])
i++;
}
while(j < arr2.length){
results.push(arr2[1])
j++;
}
return results;
}
merge([1,10,50], [2,14,99,100])
</code></pre>
<p>💭 Suggestions for improvements are welcome in the comments.</p>]]></content:encoded>
</item>
<item>
<title><![CDATA[JavaScript closures 🚀]]></title>
<link>http://irenaapp.de//blog-closures/</link>
<guid>http://irenaapp.de//blog-closures/</guid>
<pubDate>Thu, 11 Mar 2021 23:14:21 GMT</pubDate>
<description><![CDATA[Closures Closures are functions that close over their lexical environment or their scope. This allows us to access an outer function scope…]]></description>
<content:encoded><![CDATA[<h2>Closures</h2>
<p>Closures are functions that close over their lexical environment or their scope. This allows us to access an outer function scope from an inner function. We use closures in many different places. For example, if we are filtering an array of items, or if we are creating a timeout.</p>
<h2>Closure scope chains</h2>
<p>A closure is a feature in JavaScript where an inner function has access to the outer (enclosing) function’s variables — a scope chain.</p>
<p>👉 The closure has three scope chains:</p>
<ul>
<li>
<p><strong>it has access to its own scope — variables defined between its <code>curly brackets {}</code></strong></p>
</li>
<li>
<p><strong>it has access to the outer function’s variables</strong></p>
</li>
<li>
<p><strong>it has access to the global variables</strong></p>
</li>
</ul>
<h2>Closure example</h2>
<p>Let’s have a look at a simple closure example in JavaScript:</p>
<pre><code class="language-js">function outer() {
let apples = 10;
function inner() {
let plums = 20;
console.log(plums+apples);
}
return inner;
}
</code></pre>
<p>Here we have two functions:</p>
<ul>
<li>
<p>an outer function outer which has a variable b, and returns the inner function</p>
</li>
<li>
<p>an inner function inner which has its variable called a, and accesses an outer variable b, within its function body</p>
</li>
</ul>
<p>The scope of variable b is limited to the outer function, and the scope of variable a is limited to the inner function.</p>
<p>👉 Let us now invoke the <code>outer()</code> function, and store the result of the <code>outer()</code> function in a variable X. Let us then invoke the outer() function a second time and store it in variable Y.</p>
<pre><code class="language-js">
function outer() {
let apples = 10;
function inner() {
let plums = 20;
console.log(plums+apples);
}
return inner;
}
var X = outer(); //outer() invoked the first time
var Y = outer(); //outer() invoked the second time
</code></pre>
<p>👉 What happens when the <code>outer()</code> function is first invoked? 🤔</p>
<p>Variable <code>apple</code> is created, its scope is limited to the outer() function, and its value is set to 10.
The next line is a function declaration, so nothing to execute.
On the last line, return inner looks for a variable called inner, finds that this variable inner is actually a function, and so returns the entire body of the function inner.</p>
<blockquote>
<p>🛑 Note that the return statement does not execute the inner function — a function is executed only when followed by <code>()</code> — , but rather the return statement returns the entire body of the function.</p>
</blockquote>
<p>The contents returned by the return statement are stored in X.
Thus, X will store the following:</p>
<pre><code class="language-js">function inner() {
let plums=20;
console.log(plums+apples);
}
</code></pre>
<p>👉 Function <code>outer()</code> finishes execution, and all variables within the scope of <code>outer()</code> now no longer exist.</p>
<p>This last part is important to understand.</p>
<blockquote>
<p>🛑 Once a function completes its execution, any variables that were defined inside the function scope cease to exist.</p>
<p>The lifespan of a variable defined inside of a function is the lifespan of the function execution.</p>
</blockquote>
<p>What this means is that in <code>console.log(plums+apples)</code>, the variable <code>apples</code> exists only during the execution of the the <code>outer()</code> function. Once the <strong>outer</strong> function has finished execution, the variable apples no longer exists.</p>
<blockquote>
<p>🛑 When the function is executed the second time, the variables of the function are created again, and live only up until the function completes execution.</p>
</blockquote>
<p>Thus, when <code>outer()</code> is invoked the second time:</p>
<p>A new variable <code>apples</code> is created, and its <strong>scope is limited to the <code>outer()</code> function</strong>, and its value is set to 10.</p>
<p>The next line is a function declaration, so nothing to execute.</p>
<p><code>return inner</code> returns the entire body of the function inner.</p>
<p>The contents returned by the <strong>return statement</strong> are stored in <code>Y</code>.</p>
<p>Function <code>outer()</code> finishes execution, and all variables within the scope of <code>outer()</code> now no longer exist.</p>
<blockquote>
<p>👉 The important point is that when the <code>outer()</code> function is <code>invoked</code> the second time, the variable <code>apples</code> is created anew. Also, when the <code>outer() function</code> finishes execution the second time, this new variable <code>apples</code> again ceases to exist.</p>
</blockquote>
<p>This is the most important point to realize is that:</p>
<blockquote>
<p>🛑 The variables inside the functions only come into existence when the function is running, and cease to exist once the functions completes execution.</p>
</blockquote>
<p>Let's look at <code>X </code>and <code>Y</code>. Since the <code>outer()</code> function on execution returns a function, the variables X and Y are functions.</p>
<p>This can be easily verified by adding the following to the JavaScript code:</p>
<pre><code class="language-js">console.log(typeof(X)); //X is of type function
console.log(typeof(Y)); //Y is of type function
</code></pre>
<p>Since the variables X and Y are functions, we can execute them.</p>
<blockquote>
<p>A function in JavaScript can be executed by adding <code>()</code> after the function name, such as <code> X()</code> and <code>Y()</code>.</p>
</blockquote>
<pre><code class="language-js">
function outer() {
let apples = 10;
function inner() {
let plums = 20;
console.log(plums+apples);
}
return inner;
}
let X = outer();
let Y = outer();
//end of outer() function executions
X(); // X() invoked the first time
X(); // X() invoked the second time
X(); // X() invoked the third time
Y(); // Y() invoked the first time
</code></pre>
<p>When we execute <code>X()</code> and <code>Y()</code>, we are essentially executing the inner function.
Lets examine what happens when <code>X()</code> is executed the first time:</p>
<p>👉 Variable a is created, and its value is set to 20.</p>
<p>👉 JavaScript now tries to execute <code>plums + apples</code>. Here is the interesting part.</p>
<p>JavaScript knows that <code>plums</code> exists since it just created it. However, variable <code>apple</code> no longer exists.</p>
<blockquote>
<p>🛑 Since <code>apples</code> is part of the outer function, <code>apples</code> would only exist while the <code>outer()</code> function is in execution. Since the <code>outer()</code> function finished execution long before we invoked <code>X()</code>, any variables within the scope of the outer function cease to exist, and hence variable <code>apples</code> no longer exists.</p>
</blockquote>
<p>This can be handled with closures</p>
<p>👉 The inner function can access the variables of the enclosing function due to closures in JavaScript.</p>
<blockquote>
<p><strong>The inner function preserves the scope chain of the enclosing function at the time the enclosing function was executed, and thus can access the enclosing function’s variables.</strong></p>
</blockquote>
<p>In our example, the inner function had preserved the value of <code>apples=10</code> when the <code>outer()</code> function was executed, and continued to preserve (closure) it.</p>
<p>It now refers to its scope chain and notices that it does have the value of variable b within its scope chain, since it had enclosed the value of b within a closure at the point when the outer function had executed.</p>
<p>Thus, JavaScript knows <code>plums=20</code> and <code>apples=10</code>, and can calculate <code>plums+apples</code>.
You can verify this by adding the following line of code to the example above:</p>
<pre><code class="language-js">
function outer() {
let apples = 10;
function inner() {
let plums = 20;
console.log(plums+apples);
}
return inner;
}
let X = outer();
console.dir(X); //use console.dir() instead of console.log()
</code></pre>
<p>It is clear that the inner function has three scope chains:</p>
<blockquote>
<p>access to its <strong>own scope — variable <code>plums</code></strong></p>
<p><strong>access to the outer function’s variables — variable b, which it enclosed</strong></p>
<p><strong>access to any global variables that may be defined</strong></p>
</blockquote>
<pre><code class="language-js">
function outer() {
let apples = 10;
let bananas = 60;
function inner() {
let plums = 20;
console.log("plums= " + plums + " apples= " + apples);
plums++;
apples++;
}
return inner;
}
let X = outer(); // outer() invoked the first time
let Y = outer(); // outer() invoked the second time
//end of outer() function executions
X(); // X() invoked the first time
X(); // X() invoked the second time
X(); // X() invoked the third time
Y(); // Y() invoked the first time
</code></pre>
<p>🗯️ Suggestions for improvements are welcome in the comments.</p>]]></content:encoded>
</item>
<item>
<title><![CDATA[Flutter Widgets🚀]]></title>
<link>http://irenaapp.de//blog-flutter-widgets-post/</link>
<guid>http://irenaapp.de//blog-flutter-widgets-post/</guid>
<pubDate>Thu, 18 Feb 2021 23:14:21 GMT</pubDate>
<description><![CDATA[Flutter and Dart Widget Sheet Init Healthcheck Hello World Stateless Widget Required and default props Stateful Widget Combining props and…]]></description>
<content:encoded><![CDATA[<h2>Flutter and Dart Widget Sheet</h2>
<h2>Init</h2>
<pre><code class="language-bash">flutter create my_project
</code></pre>
<!-- ## Specify organization name
```bash
flutter create --org com.myorg my_project
``` -->
<h2>Healthcheck</h2>
<pre><code class="language-bash">flutter doctor
</code></pre>
<h2>Hello World</h2>
<pre><code class="language-dart">import 'package:flutter/material.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Hello world!',
home: Scaffold(
body: Center(
child: Text('Hello world'),
),
),
);
}
}
</code></pre>
<h2>Stateless Widget</h2>
<pre><code class="language-dart">import 'package:flutter/material.dart';
class Greeter extends StatelessWidget {
Greeter({Key key @required this.name}) : super(key: key);
final String name;
@override
Widget build(BuildContext context) {
return Container(
child: Text('Hello, $name'),
);
}
}
</code></pre>
<h2>Required and default props</h2>
<pre><code class="language-dart">import 'package:flutter/material.dart';
class SomeComponent extends StatelessWidget {
SomeComponent({
@required this.foo,
this.bar = 'some string',
});
final String foo;
final String bar;
@override
Widget build(BuildContext context) {
return Container(
child: Text('$foo $bar'),
);
}
}
</code></pre>
<h2>Stateful Widget</h2>
<pre><code class="language-dart">import 'package:flutter/material.dart';
class WidgetWithState extends StatefulWidget {
@override
_WidgetWithStateState createState() => _WidgetWithStateState();
}
class _WidgetWithStateState extends State<WidgetWithState> {
int counter = 0;
increment() {
setState(() {
counter++;
});
}
decrement() {
setState(() {
counter--;
});
}
@override
Widget build(BuildContext context) {
return Row(
children: <Widget>[
FlatButton(onPressed: increment, child: Text('Increment')),
FlatButton(onPressed: decrement, child: Text('Decrement')),
Text(counter.toString()),
);
}
}
</code></pre>
<h2>Combining props and state</h2>
<pre><code class="language-dart">import 'package:flutter/material.dart';
class SomeWidget extends StatefulWidget {
SomeWidget({@required this.fruit});
final String fruit;
@override
_SomeWidgetState createState() => _SomeWidgetState();
}
class _SomeWidgetState extends State<SomeWidget> {
int count = 0;
@override
Widget build(BuildContext context) {
return Container(
child: Text('$count ${widget.fruit}'),
);
}
}
class ParentWidget extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Container(
child: SomeWidget(fruit: 'oranges'),
);
}
}
</code></pre>
<h2>Lifecycle hooks</h2>
<pre><code class="language-dart">class _MyComponentState extends State<MyComponent> {
@override
void initState() {
// this method is called before the first build
super.initState();
}
@override
void didUpdateWidget(MyComponent oldWidget) {
// this method IS called when parent widget is rebuilt
super.didUpdateWidget(oldWidget);
}
@override didChangeDependencies() {
// called when InheritedWidget updates
// read more here https://api.flutter.dev/flutter/widgets/InheritedWidget-class.html
super.didChangeDependencies();
}
@override
void dispose() {
// called after widget was unmounted from widget tree
super.dispose();
}
}
</code></pre>
<h2>Android Ink effect</h2>
<pre><code class="language-dart">InkWell(
child: Text('Button'),
onTap: _onTap,
onLongPress: _onLongPress,
onDoubleTap: _onDoubleTap,
onTapCancel: _onTapCancel,
);
</code></pre>
<h2>Detecting Gestures</h2>
<pre><code class="language-dart">GestureDetector(
onTap: _onTap,
onLongPress: _onLongPress,
child: Text('Button'),
);
</code></pre>
<h2>Loading indicator</h2>
<pre><code class="language-dart">class SomeWidget extends StatefulWidget {
@override
_SomeWidgetState createState() => _SomeWidgetState();
}
class _SomeWidgetState extends State<SomeWidget> {
Future future;
@override
void initState() {
future = Future.delayed(Duration(seconds: 1));
super.initState();
}
@override
Widget build(BuildContext context) {
return FutureBuilder(
future: future,
builder: (context, snapshot) {
return snapshot.connectionState == ConnectionState.done
? Text('Loaded')
: CircularProgressIndicator();
},
);
}
}
</code></pre>
<h2>Platform specific code</h2>
<pre><code class="language-dart">import 'dart:io' show Platform;
if (Platform.isIOS) {
doSmthIOSSpecific();
}
if (Platform.isAndroid) {
doSmthAndroidSpecific();
}
</code></pre>
<h2>Hide status bar</h2>
<pre><code class="language-dart">import 'package:flutter/services.dart';
void main() {
SystemChrome.setEnabledSystemUIOverlays([]);
}
</code></pre>
<h2>Lock orientation</h2>
<pre><code class="language-dart">import 'package:flutter/services.dart';
void main() async {
await SystemChrome.setPreferredOrientations([
DeviceOrientation.portraitUp,
]);
runApp(App());
}
</code></pre>
<h2>Show alert</h2>
<pre><code class="language-dart">showDialog<void>(
context: context,
barrierDismissible: false,
builder: (BuildContext context) {
return AlertDialog(
title: Text('Alert Title'),
content: Text('My Alert Msg'),
actions: <Widget>[
FlatButton(
child: Text('Ask me later'),
onPressed: () {
print('Ask me later pressed');
Navigator.of(context).pop();
},
),
FlatButton(
child: Text('Cancel'),
onPressed: () {
print('Cancel pressed');
Navigator.of(context).pop();
},
),
FlatButton(
child: Text('OK'),
onPressed: () {
print('OK pressed');
Navigator.of(context).pop();
},
),
],
);
},
);
</code></pre>
<h2>Check if dev</h2>
<pre><code class="language-dart">bool isDev = false;
assert(isDev == true);
if (isDev) {
doSmth();
}
</code></pre>
<h2>Navigation</h2>
<pre><code class="language-dart">import 'package:flutter/material.dart';
class FirstScreen extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Center(
child: RaisedButton(
child: Text('Go to SecondScreen'),
onPressed: () => Navigator.pushNamed(context, '/second'),
),
);
}
}
class SecondScreen extends StatelessWidget {
void _pushSecondScreen(context) {
Navigator.push(context, MaterialPageRoute(builder: (context) => SecondScreen()));
}
@override
Widget build(BuildContext context) {
return Column(
children: <Widget>[
RaisedButton(
child: Text('Go back!'),
onPressed: () => Navigator.pop(context),
),
RaisedButton(
child: Text('Go to SecondScreen... again!'),
onPressed: () => _pushSecondScreen(context),
),
],
);
}
}
void main() {
runApp(MaterialApp(
initialRoute: '/',
routes: {
'/': (context) => FirstScreen(),
'/second': (context) => SecondScreen(),
},
));
}
</code></pre>
<h2>Arrays</h2>
<pre><code class="language-dart">final length = items.length;
final newItems = items..addAll(otherItems);
final allEven = items.every((item) => item % 2 == 0);
final filled = List<int>.filled(3, 42);
final even = items.where((n) => n % 2 == 0).toList();
final found = items.firstWhere((item) => item.id == 42);
final index = items.indexWhere((item) => item.id == 42);
final flat = items.expand((_) => _).toList();
final mapped = items.expand((item) => [item + 1]).toList();
items.forEach((item) => print(item));
items.asMap().forEach((index, item) => print('$item, $index'));
final includes = items.contains(42);
final indexOf = items.indexOf(42);
final joined = items.join(',');
final newItems = items.map((item) => item + 1).toList();
final item = items.removeLast();
items.add(42);
final reduced = items.fold({}, (acc, item) {
acc[item.id] = item;
return acc;
});
final reversed = items.reversed;
items.removeAt(0);
final slice = items.sublist(15, 42);
final hasOdd = items.any((item) => item % 2 == 0);
items.sort((a, b) => a - b);
items.replaceRange(15, 42, [1, 2, 3]);
items.insert(0, 42);
</code></pre>
<h2>Make http request</h2>
<pre><code class="language-dart">dependencies:
http: ^0.12.0
</code></pre>
<pre><code class="language-dart">import 'dart:convert' show json;
import 'package:http/http.dart' as http;
http.get(API_URL).then((http.Response res) {
final data = json.decode(res.body);
print(data);
});
</code></pre>
<h2>Async Await</h2>
<pre><code class="language-dart">Future<int> doSmthAsync() async {
final result = await Future.value(42);
return result;
}
class SomeClass {
method() async {
final result = await Future.value(42);
return result;
}
}
</code></pre>
<h2>JSON</h2>
<pre><code class="language-dart">import 'dart:convert' show json;
json.decode(someString);
json.encode(encodableObject);
</code></pre>
<p><strong><code>json.decode</code></strong> returns a dynamic type, which is probably not very useful</p>
<p>You should describe each entity as a Dart class with fromJson and toJson methods</p>
<pre><code class="language-dart">class User {
String displayName;
String photoUrl;
User({this.displayName, this.photoUrl});
User.fromJson(Map<String, dynamic> json)
: displayName = json['displayName'],
photoUrl = json['photoUrl'];
Map<String, dynamic> toJson() {
return {
'displayName': displayName,
'photoUrl': photoUrl,
};
}
}
final user = User.fromJson(json.decode(jsonString));
json.encode(user.toJson());
</code></pre>
<p>👉 This approach is <code>error-prone</code> (e.g. you can forget to update map key after class field was renamed), so you can use <code>json_serializable</code> as an alternative;</p>
<p>Add <code>json_annotation</code>, <code>build_runner</code> and <code>json_serializable</code> to dependencies</p>
<pre><code class="language-json">dependencies:
json_annotation: ^2.0.0
dev_dependencies:
build_runner: ^1.0.0
json_serializable: ^2.0.0
</code></pre>
<h2>Update the code</h2>
<pre><code class="language-dart">import 'package:json_annotation/json_annotation.dart';
part 'user.g.dart';
@JsonSerializable()
class User {
String displayName;
String photoUrl;
User({this.displayName this.photoUrl});
// _$UserFromJson is generated and available in user.g.dart
factory User.fromJson(Map<String, dynamic> json) {
return _$UserFromJson(json);
}
// _$UserToJson is generated and available in user.g.dart
Map<String, dynamic> toJson() => _$UserToJson(this);
}
final user = User.fromJson(json.decode(jsonString));
json.encode(user); // toJson is called by encode
</code></pre>
<p>👉 Run flutter packages pub run <code>build_runner build </code> to generate <code>serialization/deserialization</code> code;</p>
<p>To watch for changes run <strong>flutter packages pub</strong> <strong><code>run build_runner watch</code></strong></p>
<h2>Singleton</h2>
<pre><code class="language-dart">class Singleton {
static Singleton _instance;
final int prop;
factory Singleton() =>
_instance ??= new Singleton._internal();
Singleton._internal()
: prop = 42;
}
</code></pre>
<h2>Debounce</h2>
<pre><code class="language-dart">
Timer _debounce;
if (_debounce?.isActive ?? false) _debounce.cancel();
_debounce = Timer(const Duration(milliseconds: 500), () {
someFN();
});
</code></pre>]]></content:encoded>
</item>
<item>
<title><![CDATA[Gatsby - How to setup a blog 🚀]]></title>
<link>http://irenaapp.de//blog-create-a-gatsby-blog-post/</link>
<guid>http://irenaapp.de//blog-create-a-gatsby-blog-post/</guid>
<pubDate>Wed, 17 Feb 2021 23:14:21 GMT</pubDate>
<description><![CDATA[What Is Gatsby? Gatsby or GatsbyJS is a framework based on React library and GraphQL that makes it easy to create both website and web…]]></description>
<content:encoded><![CDATA[<h2>What Is Gatsby?</h2>
<p>Gatsby or GatsbyJS is a framework based on React library and GraphQL that makes it easy to create both website and web applications.</p>
<p>It is built on the Jamstack – a strategy for building websites/apps based on client-side JavaScript (or other scripts), reusable APIs and prebuilt Markup. This type of site has high performance, scalability and safety.</p>
<p>Though, Gatsby is considered a static site generator (SSG) like other Jamstack technologies (Jekyll, Next, Hugo etc) based on what it shares with them. But in reality, it can do much more than you can typically do with a static site generator.</p>
<p>You can think of Gatsby as a React framework for building complex websites and web apps. With Gatsbyjs, you are not limited to static sites. You can build a blog site, e-commerce or any complex website by using the latest tools like React, GraphQL, headless CMSs etc.</p>
<h2>Initial Setup</h2>
<p>To get started with Gatsby, you will need to have NodeJS and Git installed on your machine. With NodeJS, you can run your Gatsby JavaScript code outside of a web browser. You will also have access to its npm (node package manager) tool.</p>
<p>You can check if you have it installed by running <code>npm -v</code> and <code>node –v</code> in your terminal. The commands should return their respective versions. If not, head over to NodeJS website, download and install the latest version.</p>
<p>Gatsby allows us to start a project by using any of its starter template. There are many built-in templates officially released by the Gatsby team. Likewise, there are hundreds of other once that are created by third-party developers.</p>
<p>With these templates, you can create all sort of interesting sites and applications.</p>
<p>The goal here is to explore the fundamental features, a Gatsby starter is used with the minimum feature – i.e no plugins and no boilerplate.</p>
<h2>How to create a Blog with Gatsby ? 🤔</h2>
<p>👉 creating a blog with Gatsby and deploying it on Netlify</p>
<p>The convention to install a new Gatsby starter through the CLI is:</p>
<pre><code class="language-bash">gatsby new [PROJECT_DIRECTORY] [STARTER_URL]
</code></pre>
<h2>Gatsby Starter Templates</h2>
<p><a href="https://www.gatsbyjs.com/starters/?">Gatsby Starter Templates</a></p>
<p>👉 Gatsby Starter Blog template has the following features—</p>
<blockquote>
<ul>
<li><strong>SEO</strong></li>
<li><strong>Category Tags</strong></li>
<li><strong>Tag pages</strong></li>
<li><strong>Dark/Light modes</strong></li>
</ul>
</blockquote>
<h2>Prerequisites</h2>
<pre><code class="language-bash">npm / yarn
git / github
</code></pre>
<p>React (not needed if you want to use the template as it is)
Let's get started
Create a new repository on GitHub and clone it locally.</p>
<pre><code class="language-bash">git clone https://github.com/your-username/your-blog
cd your-blog
</code></pre>
<p>Install the gatsby CLI</p>
<pre><code class="language-bash">npm install -g gatsby-cli
</code></pre>
<p>Create a new site using the starter site into app directory</p>
<pre><code class="language-bash">gatsby new app https://github.com/ihsavru/gatsby-starter-peach
</code></pre>
<p>Move the contents of the app directory to the root directory.</p>
<pre><code class="language-bash">mv app/* .
rm -rf app
</code></pre>
<p>🛑 👉 Before we take a look inside the project folder, let's run the development server. To do this, we will run one of the scripts that Gatsby provides. If you open the package.json file in the root and check the scripts property, you will see something like this:</p>
<pre><code class="language-json">"scripts": {
"build": "gatsby build",
"develop": "gatsby develop",
"format": "prettier --write \"**/*.{js,jsx,json,md}\"",
"start": "npm run develop",
"serve": "gatsby serve",
"clean": "gatsby clean",
"test": "echo \"Write tests! -> https://gatsby.dev/unit-testing\" && exit 1"
},
</code></pre>
<p>👉 Your focus here should be on the <strong><code>develop</code></strong> script. This will allow you to start the development server and build your project locally. This script also comes with live reload so that changes are reflected in real time.</p>
<p>👉 You can start your Gatsby site either from your computer terminal or the integrated terminal of VsCode (if you are using it). From the computer terminal, navigate into your project directory:</p>
<h2>Development</h2>
<p>Run the development server.</p>
<pre><code class="language-bash">gatsby develop
</code></pre>
<p>You can make any changes you want and it will be reflected on <a href="http://localhost:8000/">http://localhost:8000/</a></p>
<p>Open site-meta-data.json and edit the fields accordingly. You might have to restart your development server to see these changes being reflected. (You can skip these changes and edit later using Netlify CMS after deploying)</p>
<p>Next open static/admin/config.yml and change iren/gatsby-starter-blog to your repo.</p>
<p>👉 create a <code>.gitignore file</code></p>
<p>Add the code below 👇</p>
<pre><code class="language-bash">node_modules
public
.cache
.DS_Store
</code></pre>
<p>After you are done, commit your changes and push it to GitHub.</p>
<pre><code class="language-bash">git add .
git commit -m "your commit message here"
git push
</code></pre>
<h2>Inside the Project Directory</h2>
<p>Having worked with React, I you should be familiar with the project (folders and files) structure, but I will quickly touch some of the important folders and files.</p>
<p>👉 The <code>node_modules</code> folder contains all the third-party libraries as well as Gatsby itself. This directory will also contain packages you’ll be installing through npm later in the tutorial. The public folder will contain the public asset of your site and will hold your static files.</p>
<p>👉 The <code>src</code> folder will contain all of your working files. This is where you’ll spend most of your time. Inside this folder, we have the pages directory. This is a very important directory inside the Gatsby project. Any files inside this folder automatically become static pages with paths based on their filename.</p>
<p>At the moment, we have <code>index.js</code> present in the pages folder. And as you know, the <code>index</code> file <strong>always references the home page</strong>. This is why the content of this file is being rendered in the frontend.</p>
<p>👉 The <code>gatsby-config.js</code> file is where you configure your Gatsby site. In this file, you set the site title, description, the Gatsby plugins to include and some other configuration.</p>
<p>👉 The <code>package.json </code>contains information about your site. It has some dependencies of libraries that are currently installed and if you install other packages, they will be listed as well.</p>
<p>👉 The <code>src/pages</code> folder holds the file for the site static pages.
👉 Go inside the folder and open the <code>index.js</code> file. The code in this file is a simple React component that is rendering a simple "Hello world!" on the screen.</p>
<h2>Working With Gatsby Pages</h2>
<p>The focus will be on the <code>src/pages</code> directory. At the moment, we only have the index.js file in this folder.</p>
<p>When it comes to page creation, this directory is where Gatsby looks when it is figuring out what static pages your site needs. So all the files you put inside this directory will represent your site pages.</p>
<p>So let’s get started with the <code>index.js</code> file.</p>
<pre><code class="language-JS">import React from "react"
const Index = () => {
return (
<div>
<h1>Home page</h1>
<h2>I am Irene, a teacher and a web developer</h2>
</div>
)
}
export default Index
</code></pre>
<h2>Generating the files</h2>
<p>It starts by looking at the <code>src/pages</code> folder to figure out which static pages it should create. In our case, it realizes we only have one file, index.js. Meaning our site will only have a single page.</p>
<p>Now the name of the file is also important. Here, the file is called index.js. This is similar to how <code>index.html</code> will be the default page for a website homepage.</p>
<p>👉 Gatsby, <code>index.js</code> will be the default homepage. To create a new page, all you have to do is to add a new file to the src/pages directory.</p>
<h2>Deployment</h2>
<p>👉 Create an account on <strong>Netlify</strong></p>
<p>After logging in, go to Sites</p>
<p>👉 click on <strong>"New Site from git"</strong></p>
<p>Complete the following steps - Connect to GitHub,
select your repository and deploy site.</p>
<p>Set <code>build</code> command to <code>gatsby build</code> and publish directory to <code>public</code>.</p>
<h2>Start creating your Posts</h2>
<p>Go to your deployed Netlify site and go to the Admin page - <a href="https://your-site.netlify.app/admin">https://your-site.netlify.app/admin</a>
Log in using GitHub.</p>
<p>Now you can edit your blogs as well as your site metadata from here itself!
You can delete the sample blogs that come with the template and add your own.</p>
<h2>Go to Starter Files Code 👇</h2>
<p><a href="https://github.com/CodeCrunchies/gatsby-blog">Sample Starter Blog</a></p>]]></content:encoded>
</item>
<item>
<title><![CDATA[Flutter Basics🚀]]></title>
<link>http://irenaapp.de//blog-flutter-post/</link>
<guid>http://irenaapp.de//blog-flutter-post/</guid>
<pubDate>Fri, 12 Feb 2021 23:14:21 GMT</pubDate>
<description><![CDATA[Core Basics Flutter includes a modern react-style framework, a 2D rendering engine, ready-made widgets, and development tools. These…]]></description>
<content:encoded><![CDATA[<h2>Core Basics</h2>
<p>Flutter includes a modern react-style framework, a 2D rendering engine, ready-made widgets, and development tools. These components work together to help design, build, test, and debug apps. Everything is organised around a few core principles.</p>
<blockquote>
<p>👉 Widgets are the basic building blocks of a Flutter app’s user interface. Unlike other frameworks that separate views, view controllers, layouts, and other properties, Flutter has a consistent, unified object model: <strong>the widget that works across the app</strong>. 🤔</p>
</blockquote>
<p>🛑 <strong>Widgets</strong> form a hierarchy based on the composition they work with. Each widget can be nested inside, and inherits properties from its parent. There is no separate “application” object. Instead, the root widget serves this role & handles the state of the app.</p>
<p>👉 Flutter and Chrome use the same rendering engine — SKIA. Instead of interacting with native APIs, it controls every pixel on the screen, which gives it the much necessary freedom from the legacy baggage as well as the performance it has.</p>
<p>Some commands I run while setting up Android studio and Flutter on my machine:</p>
<pre><code class="language-bash">echo 'export ANDROID_HOME=/Users/$USER/Library/Android/sdk' >> ~/.bash_profile
echo 'export PATH=${PATH}:$ANDROID_HOME/tools:$ANDROID_HOME/platform-tools' >> ~/.bash_profile
</code></pre>
<p>Supported Commands for update on macOS:</p>
<pre><code class="language-bash">update sdk -u
Supported commands are:
android list target
android list avd
android list device
android create avd
android move avd
android delete avd
android list sdk
android update sdk
</code></pre>
<pre><code class="language-bash">flutter doctor --android-licenses
</code></pre>
<p>👉 In case you face this error run 👉</p>
<pre><code class="language-bash">flutter doctor --android-licenses
ERROR: JAVA_HOME is set to an invalid directory: /usr/libexec/java_home
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation.
</code></pre>
<p>run the commands: 👇</p>
<pre><code class="language-bash">export JAVA_HOME=`/usr/libexec/java_home`
echo export "JAVA_HOME=\$(/usr/libexec/java_home)" >> ~/.bash_profile
</code></pre>
<pre><code class="language-bash">brew install android-platform-tools
</code></pre>
<h2>Installing Flutter with Homebrew</h2>
<pre><code class="language-bash">brew install --cask flutter
</code></pre>
<pre><code class="language-bash">flutter upgrade
</code></pre>
<h2>create a flutter app</h2>
<p>step 1: 👉 Navigate to desired folder where you want to locate your app;</p>
<pre><code class="language-BASH">cd development/
</code></pre>
<p>step 2: 👉 Run the command:</p>
<pre><code class="language-bash">flutter create first_app
</code></pre>
<pre><code class="language-bash">In order to run your application, type:
$ cd first_app
$ flutter run
Your application code is in first_app/lib/main.dart.
</code></pre>
<pre><code class="language-bash">
Flutter run key commands.
r Hot reload. 🔥🔥🔥
R Hot restart.
h Repeat this help message.
d Detach (terminate "flutter run" but leave application running).
c Clear the screen
q Quit (terminate the application on the device).
</code></pre>
<h2>XCode</h2>
<pre><code class="language-bash">
$ sudo xcode-select --switch /Applications/Xcode.app/Contents/Developer
$ sudo xcodebuild -license
$ open -a Simulator
</code></pre>]]></content:encoded>
</item>
<item>
<title><![CDATA[React-Native views&text🚀]]></title>
<link>http://irenaapp.de//blog-react-native-post/</link>
<guid>http://irenaapp.de//blog-react-native-post/</guid>
<pubDate>Fri, 12 Feb 2021 23:14:21 GMT</pubDate>
<description><![CDATA[views&text There is no DOM on mobile. Where we previously used <div />, we need to use <View /> and where we used <span />, the component we…]]></description>
<content:encoded><![CDATA[<h2>views&text</h2>
<p>There is no DOM on mobile. Where we previously used <code><div /></code>, we need to use <code><View /></code> and where we used <code><span /></code>, the component we need here is <code><Text /></code>.</p>
<blockquote>
<p>The <strong><code>View</code></strong> is the fundamental component of <strong>React Native</strong> for building a user interface. It is a container that supports layout with flexbox, style, touch handling, and accessibility controls. It maps directly to the native view similar to whatever platform on React Native app is running on. It displays the components regardless with UIView, <code><div></code>, android.view, etc.</p>
</blockquote>
<p>🛑 <code><Text></code> and <code><View> </code> are the most important most-used components built in to React Native
<code><View></code> is your #1 component if you need to group and structure content ( provide a layout) or if you want to style something like a container, <code><View> </code>uses Flexbox to organize its children
A <code><View> </code>can hold as many child components as you need and it also works with any kind of child component - it can hold <code><Text></code> components, other <code><View></code>s <strong>(for nested containers/ layouts)</strong>,** <code><Image></code>s, custom components etc.</p>
<p>If you need scrolling, you should consider using a <code><ScrollView></code> - you could wrap your <code><View></code> with it or replace your <code><View></code> (that depends on your layout and styling). Please note, that due to its scrollable nature, Flexbox works a bit differently on a <ScrollView></p>
<p><strong><code><Text></code></strong> is also important. As its name suggests, you can use it for outputting text (of any length). You can also nest other <Text> components into a <Text>. You can also have nested <View>s inside of a <Text> but that comes with certain caveats you should watch out for</p>
<p>👉 <code><Text></code> does NOT use <strong>Flexbox for organizing its content</strong> (i.e. the text or nested components). Instead, text inside of <Text> automatically fills a line as you would expect it and wraps into a new line if the text is too long for the available <Text> width.
You can avoid wrapping by setting the numberOfLines prop, possibly combined with ellipsizeMode.</p>
<pre><code class="language-js"><Text numberOfLines={1} ellipsizeMode="tail">
This text will never wrap into a new line, instead it will be cut off like this if it is too lon...
</Text>
</code></pre>
<p>🛑 When adding styles to a <code><Text></code> (no matter if that happens via inline styles or a StyleSheet object), the styles will be shared with any nested <Text> components.</p>
<p>This differs from the behaviour of <code><View></code> (or any other component - <Text> is the exception). Styles are only applied to the component to which you add them. Styles are never shared with any child component!</p>
<p>The <code>App.js</code> file contains the code for the main React component which gets bootstrapped in the index.js file using the AppRegistry.registerComponent() method:</p>
<pre><code class="language-js">import {AppRegistry} from 'react-native';
import App from './App';
import {name as appName} from './app.json';
AppRegistry.registerComponent(appName, () => App);
</code></pre>
<p>This will be considered as the root component of our application.</p>
<p>Open the <code>App.js</code> file, and remove all the existing (slightly advanced) code then replace it with this simple code instead:</p>
<pre><code class="language-js">import React from 'react';
import {
View,
Text,
} from 'react-native';
const App = () => {
return (
<View style=>
<Text>Hello, world!</Text>
</View>
);
};
export default App;
</code></pre>
<p>Save the file, open your emulator and press <strong><code>R</code></strong> twice in the keyboard.</p>]]></content:encoded>
</item>
<item>
<title><![CDATA[How to install ZSH on Fedora🚀]]></title>
<link>http://irenaapp.de//blog-zsh-shell-post/</link>
<guid>http://irenaapp.de//blog-zsh-shell-post/</guid>
<pubDate>Fri, 12 Feb 2021 23:14:21 GMT</pubDate>
<description><![CDATA[Terminal Setup - Terminator + ZSH + Powerlevel10k terminal is more than just a black screen to type in. It usually runs a shell, so called…]]></description>
<content:encoded><![CDATA[<h2>Terminal Setup - Terminator + ZSH + Powerlevel10k</h2>
<p>terminal is more than just a black screen to type in. It usually runs a shell, so called because it wraps around the kernel. The shell is a text-based interface that lets you run commands on the system. It’s also sometimes called a command line interpreter or CLI. Fedora, like most Linux distributions, comes with bash as the default shell.</p>
<p>This article focuses on the Z Shell, or zsh.</p>
<p>Bash is a rewrite of the old Bourne shell (sh) that shipped in UNIX. Zsh is intended to be friendlier than bash, through better interaction. Some of its useful features are:</p>
<p>Programmable command line completion
Shared command history between running shell sessions
Spelling correction
Loadable modules
Interactive selection of files and folders</p>
<h2>What will be setup?</h2>
<p>Terminator terminal to support splitting the terminal screen vertically and horizontally into multiple windows. Extremely useful when working with distributed systems like blockchain.
ZSH framework to add productivity plugins and custom color themes.
Powerlevel10k for "speed, flexibility and out-of-the-box experience.</p>
<h2>Run System Update</h2>
<pre><code class="language-bash">dnf update
</code></pre>
<h2>Installing Zsh in Fedora System</h2>
<p>Zsh can be found in the Fedora repositories and can be installed using the following dnf command.</p>
<p>Zsh is available in the Fedora repositories. To install, run this command:</p>
<pre><code class="language-bash">$ sudo dnf install zsh
</code></pre>
<pre><code class="language-bash">zsh --version
</code></pre>
<p>or</p>
<h2>Install oh-my-zsh on Fedora 33</h2>
<p>Oh-my-Zsh framework can be installed by either using the curl or wget commands as shown below;</p>
<pre><code class="language-bash">sudo dnf install wget curl
sh -c "$(curl -fsSL https://raw.githubusercontent.com/robbyrussell/oh-my-zsh/master/tools/install.sh)"
</code></pre>
<p>or</p>
<pre><code class="language-bash">sh -c "$(wget https://raw.githubusercontent.com/robbyrussell/oh-my-zsh/master/tools/install.sh -O -)"
</code></pre>
<h2>Using zsh</h2>
<p>To start using it, just type zsh and the new shell prompts you with a first run wizard. This wizard helps you configure initial features, like history behavior and auto-completion.</p>
<h2>Making Zsh as Default Shell in Fedora</h2>
<p>Zsh offers a lot of plugins, like zsh-syntax-highlighting, and the famous “Oh my zsh” (check out its page here). You might want to make it the default, so it runs whenever you start a session or open a terminal. To do this, use the chsh (“change shell”) command:</p>
<pre><code class="language-bash">$ chsh -s $(which zsh)
</code></pre>
<p>This command tells the system that you want to set (-s) your default shell to the correct location of the shell ( zsh).</p>
<h2>PowerLevel10k Theme</h2>
<p>The great thing about ZSH is the level of ization possible. I found this theme which looks pretty solid: <a href="https://github.com/romkatv/powerlevel10k#meslo-nerd-font-patched-for-powerlevel10k">https://github.com/romkatv/powerlevel10k#meslo-nerd-font-patched-for-powerlevel10k</a></p>
<h2>Install the theme</h2>
<pre><code class="language-bash">git clone --depth=1 https://github.com/romkatv/powerlevel10k.git ~/powerlevel10k
echo 'source ~/powerlevel10k/powerlevel10k.zsh-theme' >>! ~/.zshrc
source ~/.zshrc
</code></pre>
<h2>Adding emojies</h2>
<p>When it comes to Chrome, you have basically two ways how to display color emojis. You can either install EmojiOne or Google Noto Color Emoji. Although I first tried to use the former, I was not able to make it work so I decided to stick with the latter.</p>
<p>You first need to install a package with this font by running the following command:</p>
<pre><code class="language-bash">sudo dnf install google-noto-emoji-color-fonts
</code></pre>
<p>Then you need to create file : $ <code>~/.config/fontconfig/fonts.conf</code> with the following content:</p>
<pre><code class="language-xml"><?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE fontconfig SYSTEM "fonts.dtd">
<fontconfig>
<alias>
<family>serif</family>
<prefer>
<family>Noto Color Emoji</family>
</prefer>
</alias>
<alias>
<family>sans-serif</family>
<prefer>
<family>Noto Color Emoji</family>
</prefer>
</alias>
<alias>
<family>monospace</family>
<prefer>
<family>Noto Color Emoji</family>
</prefer>
</alias>
</fontconfig>
</code></pre>
<p>Finally, you need to apply the new configuration by running:</p>
<pre><code class="language-bash">fc-cache -f
</code></pre>
<p>Now, you just need to restart Chrome
<a href="https://wiki.gnome.org/Design/OS/Emoji">Emojies</a>
<a href="https://github.com/hbons/gnome-emoji">Emojies</a>
<a href="https://www.joypixels.com/">Emojies</a>
<a href="https://archlinux.org/packages/extra/x86_64/cairo/">Cairo Emojies</a></p>
<p>Installation Instructions</p>
<pre><code class="language-bash"># yum update
# yum install yum-plugin-copr
# yum copr enable fujiwara/cairo
# yum install freetype cairo fontconfig google-noto-emoji-color-fonts
</code></pre>
<p><a href="https://copr.fedorainfracloud.org/coprs/fujiwara/cairo/">Fujiwara Cairo Emojies</a></p>]]></content:encoded>
</item>
<item>
<title><![CDATA[How to FLEX in React 🤖]]></title>
<link>http://irenaapp.de//blog-styles/</link>
<guid>http://irenaapp.de//blog-styles/</guid>
<pubDate>Thu, 11 Feb 2021 23:14:21 GMT</pubDate>
<description><![CDATA[: Using Flexbox in React components to create flexible layouts. How to Flex in React? 🤔 Flexbox helps to organize the blocks of code as…]]></description>
<content:encoded><![CDATA[<p><em>: Using Flexbox in React components to create flexible layouts.</em></p>
<h2>How to Flex in React? 🤔</h2>
<p>Flexbox helps to organize the blocks of code as structured boxes, while React allows you to render these boxes as reusable <strong>components</strong>. Combining Flexbox and React lets you create responsive layouts without relying on heavy CSS frameworks.</p>
<p>With Flexbox and frontend frameworks like React, there is no reason to use bulky CSS frameworks anymore. The key idea is to use <code>display: flex</code> in style to control the ratios, alignment, and order of components. This makes your UI <strong>scalable, maintainable, and adaptive to different screen sizes</strong>.</p>
<hr>
<h3>Why Flexbox?</h3>
<p>Flexbox simplifies layout design:</p>
<ul>
<li>Align items horizontally or vertically with minimal code.</li>
<li>Control spacing dynamically without hard-coded widths or margins.</li>
<li>Easily reorder elements without changing the HTML structure.</li>
<li>Create responsive layouts that adjust automatically to screen size.</li>
<li>Combine with React’s reusable components for scalable UI design.</li>
</ul>
<hr>
<h3>Using Flex in React</h3>
<p>In React, you can pass <strong>inline styles</strong>, <strong>CSS modules</strong>, or <strong>styled-components</strong> to apply Flexbox.</p>
<blockquote>
<p><strong>Example 1: Inline Flex</strong></p>
<pre><code class="language-jsx">function FlexContainer() {
return (
<div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
<div>Item 1</div>
<div>Item 2</div>
<div>Item 3</div>
</div>
);
}
</code></pre>
<p>The container evenly spaces the items horizontally and aligns them vertically in the center. This is ideal for headers, toolbars, or navigation bars.</p>
</blockquote>
<hr>
<blockquote>
<p><strong>Example 2: Flex with CSS Modules</strong></p>
<pre><code class="language-css">/* styles.module.css */
.container {
display: flex;
flex-direction: row;
gap: 20px;
padding: 10px;
}
</code></pre>
<pre><code class="language-jsx">import styles from './styles.module.css';
function FlexModule() {
return (
<div className={styles.container}>
<div>Card 1</div>
<div>Card 2</div>
<div>Card 3</div>
</div>
);
}
</code></pre>
<p>Using CSS modules keeps styles <strong>clean, maintainable, and scoped</strong>, avoiding conflicts in larger projects.</p>
</blockquote>
<hr>
<h3>Controlling Ratios with Flex</h3>
<p>Flexbox allows you to define <strong>how much space each item takes</strong> using <code>flex-grow</code>, <code>flex-shrink</code>, and <code>flex-basis</code>.</p>
<blockquote>
<pre><code class="language-jsx"><div style={{ display: 'flex' }}>
<div style={{ flex: 1 }}>Sidebar</div>
<div style={{ flex: 3 }}>Main Content</div>
</div>
</code></pre>
</blockquote>
<blockquote>
<p>In this example, the main content takes <strong>three times</strong> the width of the sidebar. Flex ratios allow layouts to remain responsive without hardcoding widths in pixels.</p>
</blockquote>
<hr>
<h3>Flex Direction and Alignment</h3>
<p>Flexbox supports <code>flex-direction</code>, <code>justify-content</code>, and <code>align-items</code>, which control the <strong>layout flow and alignment</strong>:</p>
<ul>
<li><code>flex-direction: row | column</code> → layout horizontally or vertically</li>
<li><code>justify-content: flex-start | center | space-between</code> → horizontal alignment</li>
<li><code>align-items: flex-start | center | stretch</code> → vertical alignment</li>
</ul>
<blockquote>
<p><strong>Example: Vertical Layout</strong></p>
<pre><code class="language-jsx"><div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center' }}>
<div>Header</div>
<div>Main</div>
<div>Footer</div>
</div>
</code></pre>
</blockquote>
<hr>
<h3>Tips for React + Flexbox</h3>
<ul>
<li>Prefer <strong>CSS modules</strong> or <strong>styled-components</strong> for maintainable styles.</li>
<li>Combine Flexbox with <strong>React component hierarchy</strong> for reusable UI blocks.</li>
<li>Test your components on <strong>different screen sizes</strong> to ensure responsiveness.</li>
<li>Use <strong>gap</strong> property for spacing between elements instead of margins for cleaner layouts.</li>
</ul>
<hr>
<h3>Conclusion</h3>
<p>Using Flexbox in React gives you <strong>full control over layouts</strong>, eliminates the need for heavy CSS frameworks, and makes your components fully responsive. Once you master flex ratios, alignment, and directions, you can build <strong>complex UIs</strong> efficiently.</p>
<blockquote>
<p>“Flexibility in design comes from flexible components, not rigid frameworks.”</p>
</blockquote>
<hr>]]></content:encoded>
</item>
<item>
<title><![CDATA[Using Express validator 🤔]]></title>
<link>http://irenaapp.de//blog-backend-express-post/</link>
<guid>http://irenaapp.de//blog-backend-express-post/</guid>
<pubDate>Tue, 26 Jan 2021 23:14:21 GMT</pubDate>
<description><![CDATA[Validating input in Express using express-validator understand how to use express-validator module to make the input validation from the…]]></description>
<content:encoded><![CDATA[<h3>Validating input in Express using express-validator</h3>
<p>understand how to use express-validator module to make the input validation from the server side. We will build a basic Node/Express app with the help of a couple of npm packages such as express-session, express-validator, cookie-parser, etc.</p>
<p>👉 ⚠️ Express validator is one of the many <strong>npm packages</strong> for validating a request in an express application.</p>
<pre><code class="language-js">// ...rest of the initial code omitted for simplicity.
const { check, validationResult } = require('express-validator')
app.post(
'/user',
[
// username must be an email
check('username').isEmail(),
// password must be at least 5 chars long
check('password').isLength({ min: 5 }),
],
(req, res) => {
// Finds the validation errors in this request and wraps them in an object with handy functions
const errors = validationResult(req)
if (!errors.isEmpty()) {
return res.status(422).json({ errors: errors.array() })
}
User.create({
username: req.body.username,
password: req.body.password,
}).then(user => res.json(user))
}
)
</code></pre>
<p>That pattern may be okay for a very simple use case but when usage scales, it'd be difficult for the codebase to be maintained and also it makes the route definition not readable.</p>
<p>In this article, I'll be showing how the validation above can be made more readable and easier to maintain.</p>
<h3>Step 1</h3>
<p>Create a file named <code>validator.js</code>
Inside the <code>validator.js</code>, we are going to add two functions, one of the functions will hold the validation rules, while the second will contain the function the does the actual validation.</p>
<p>Copy the snippet below 👇 into the <code>validator.js</code></p>
<pre><code class="language-js">
const { body, validationResult } = require('express-validator')
const userValidationRules = () => {
return [
// username must be an email
body('username').isEmail(),
// password must be at least 5 chars long
body('password').isLength({ min: 5 }),
]
}
const validate = (req, res, next) => {
const errors = validationResult(req)
if (errors.isEmpty()) {
return next()
}
const extractedErrors = []
errors.array().map(err => extractedErrors.push({ [err.param]: err.msg }))
return res.status(422).json({
errors: extractedErrors,
})
}
module.exports = {
userValidationRules,
validate,
}
</code></pre>
<h3>Step 2</h3>
<p>Now re-writing the initial snippet above, we'd have:</p>
<pre><code class="language-js">
const { userValidationRules, validate } = require('./validator.js')
app.post('/user', userValidationRules(), validate, (req, res) => {
User.create({
username: req.body.username,
password: req.body.password,
}).then(user => res.json(user))
})
</code></pre>
<p>Now if you try to register a user without meeting the specification for the user data, the validation error response would look like shown below:</p>
<pre><code class="language-js">{
"errors": [
{
"username": "username must be an email"
},
{
"password": "password must be at least 5 chars long"
},
]
}
</code></pre>
<p>With this method in place, you can define the validation rules for each route or module in a separate file as you may deem fit and then chain it with the validate middleware. That way the code looks much cleaner, easier to read and easier to maintain.</p>
<p><a href="https://express-validator.github.io/docs/">Express Validator Docs</a></p>
<h3>Going further and hands on more practice 👇</h3>
<h4>Why Server-side Validation ❓ 🤔</h4>
<p>Well, security is the most significant expect when it comes to safety and security; a server must not have total faith on the client-side. The client-side validation can be deciphered, or data can be manipulated by just turning off the JavaScript in the browser.
Validation has a significant role in web or mobile application security. No matter whether you build your app using the Express framework or any other Node.js framework.
In this tutorial, we will look at how to validate form data in an Express/Node.js app using a popular open-source npm package called express-validator.</p>
<h3>Why express-validator is useful?</h3>
<p>As per their official documentation:
express-validator is a set of <strong>express.js middlewares</strong> that wraps <code>validator.js</code> validator and sanitizer functions.</p>
<p>👉 Check API</p>
<p>👉 Filter API</p>
<p>👉 Schema Validation</p>
<p>👉 Validation chain API</p>
<p>👉 Validation Result API</p>
<p>👉 Custom Error Messages</p>
<p>👉 Sanitization chain API</p>
<p>👉 Validation MiddleWares</p>
<h3>Input Validation with Express Validator Example</h3>
<p>We will create an Express API to make the POST request to the server. If the request gets failed, then we will display the form validation errors for name, email, password and confirm password input fields.</p>
<p>We will install Bootstrap 4 to build the basic form and to display the HTML partials we will use up express-hbs module in our Express/Node app.</p>
<h3>Set Up Express/Node Form Validation Project</h3>
<p>Create express input validation project folder for by running the below command.</p>
<pre><code class="language-bash">mkdir express-node-form-validation
</code></pre>
<p>Get inside the project directory.</p>
<pre><code class="language-bash">cd express-node-form-validation
</code></pre>
<p>Run command to create package.json:</p>
<pre><code class="language-bash">npm init
</code></pre>
<p>Next, install nodemon module with --save-dev attribute for development purpose. This module takes care the server restarting process.</p>
<pre><code class="language-bash">npm install nodemon --save-dev
</code></pre>
<h3>Install Express Validator Package</h3>
<p>Next, install following module from npm to build express and node app.</p>
<pre><code class="language-bash">npm install body-parser cookie-parser cors express-session --save
</code></pre>
<p>In order to implement input validation we need to install express and express-validator modules.</p>
<pre><code class="language-bash">npm install express express-validator --save
</code></pre>
<h4>Configure Node/Express Server</h4>
<p>Create <code>app.js</code> file, here in this file we will keep node server settings. Then, go to package.json file and add start: “nodemon app.js” property inside the scripts object and also define main: "app.js" property.</p>
<p>Here is the final <code>package.json</code> file.</p>
<pre><code class="language-json">// package.json
{
"name": "express-node-server-side-form-validation",
"version": "1.0.0",
"description": "Express and Node.js server-side form validation tutorial with examples",
"main": "app.js",
"scripts": {
"start": "nodemon app.js",
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "Irie",
"license": "ISC",
"dependencies": {
"body-parser": "^1.19.0",
"cookie-parser": "^1.4.4",
"cors": "^2.8.5",
"express": "^4.17.1",
"express-hbs": "^2.1.2",
"express-session": "^1.17.0",
"express-validator": "^6.2.0"
},
"devDependencies": {
"nodemon": "^1.19.4"
}
}
</code></pre>
<p>Next, go to <code>app.js</code> file and include the following code in it.</p>
<pre><code class="language-js">const express = require('express');
const bodyParser = require('body-parser');
const cors = require('cors');
const cookieParser = require('cookie-parser');
const session = require('express-session');
// Express settings
const app = express();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
extended: false
}));
app.use(cors());
app.use(cookieParser());
app.use(session({
secret: 'positronx',
saveUninitialized: false,
resave: false
}));
// Define PORT
const port = process.env.PORT || 3000;
const server = app.listen(port, () => {
console.log('Connected to port ' + port)
})
</code></pre>
<h3>Set Up Express Handlebars View Engine</h3>
<p>Now, we need to install express-hbs module, It’s a handlbars templating view engine. Run below command to install the module.</p>
<pre><code class="language-js">npm install express-hbs --save
</code></pre>
<p>Next step, create <strong>views</strong> folder inside the <strong>express input validation</strong> project folder. And, also create partials folder within the views folder, following will be the folder architecture <strong>views > partials</strong>.</p>
<p>Then, create <strong>public</strong> folder inside the express validation folder. Also, create css and js folder inside the public folder.</p>
<p>Next, Download Bootstrap and take <strong>bootstrap.min.css</strong> and <strong>bootstrap.min.js</strong> files and put inside their respective folders inside the public folder.</p>
<p>👉 Create <strong>user.hbs</strong> file using Bootstrap inside views/partials/ folder, add the following code.</p>
<pre><code class="language-js"><!-- user.hbs -->
<html lang="en">
<head>
<title>Express Node Form Validation</title>
<link href="../../public/css/bootstrap.min.css" rel="stylesheet" type="text/css">
<link href="../../public/css/styles.css" rel="stylesheet" type="text/css">
</head>
<body>
<nav class="navbar navbar-dark bg-primary">
<a class="navbar-brand" href="#">Express Form Data Validation</a>
</nav>
<div class="container">
<div class="col-md-12">
<form method="post" action="">
<div class="form-group">
<label>Name</label>
<input type="text" class="form-control" name="name" />
</div>
<div class="form-group">
<label>Email</label>
<input type="text" class="form-control" name="email" />
</div>
<div class="form-group">
<label>Password</label>
<input type="password" class="form-control" name="password" />
</div>
<div class="form-group">
<label>Confirm Password</label>
<input type="password" class="form-control" name="confirm_password" />
</div>
<div class="form-group">
<button type="submit" class="btn btn-danger btn-block">Create</button>
</div>
</form>
</div>
</div>
</body>
</html>
</code></pre>
<p>Next, add express handlebars view engine settings in <code>app.js</code> file.</p>
<pre><code class="language-js">// app.js
const hbs = require('express-hbs');
// Serve static resources
app.use('/public', express.static('public'));
// Render View
app.engine('hbs', hbs.express4({
partialsDir: __dirname + '/views/partials'
}));
app.set('view engine', 'hbs');
app.set('views', __dirname + '/views/partials');
</code></pre>
<p>Run the following command bellow and check the user form in the browser in your localhost.</p>
<pre><code class="language-bash">
npm start
</code></pre>
<h3>Implement Input Validation in Express Routes</h3>
<p>Now, <strong>create express routers</strong> to make the <strong>POST and GET requests</strong> using Express.js. Create 📁<code>routes</code> folder and create <code>user.routes.js</code> file inside of it and paste the given below code.</p>
<pre><code class="language-js">
// routes/user.routes.js
const express = require("express");
const session = require('express-session');
const router = express.Router();
const { check, validationResult } = require('express-validator');
router.post('/create-user',
[
check('name')
.not()
.isEmpty()
.withMessage('Name is required'),
check('email', 'Email is required')
.isEmail(),
check('password', 'Password is required')
.isLength({ min: 1 })
.custom((val, { req, loc, path }) => {
if (val !== req.body.confirm_password) {
throw new Error("Passwords don't match");
} else {
return value;
}
}),
], (req, res) => {
var errors = validationResult(req).array();
if (errors) {
req.session.errors = errors;
req.session.success = false;
res.redirect('/user');
} else {
req.session.success = true;
res.redirect('/user');
}
});
router.get('/', function (req, res) {
res.render('user', {
success: req.session.success,
errors: req.session.errors
});
req.session.errors = null;
});
module.exports = router;
</code></pre>
<p>👉 Import check, validationResult class from the express-validator module in the <code>user.routes.js</code> file.</p>
<p>👉 Add input validation with <strong>HTTP POST request</strong> declare the errors array as a second argument in the <code>router.post()</code> method.</p>
<p>We declared the express validators check() method and passed the input validation name in it, and used the <code>.not()</code>, <code>.isEmpty()</code> methods in it. To display the error message the <code>.withMessage()</code> method was used.</p>
<p>The <code>.isEmail()</code> does the email validation in the Express API.</p>
<p>To make the password required and confirm password validation, we declare the custom method.</p>
<p>👉 Next, go to app.js and add the express user router.</p>
<pre><code class="language-js">// app.js
// User router
const user = require('./routes/user.routes');
// Initiate API
app.use('/user', user)
</code></pre>
<h3>Show Server-Side Validation Errors in Node App</h3>
<p>To show the validation errors in the handlebar view template. Go, to views/partials/user.hbs file and add the following code in it.</p>
<pre><code class="language-js"><!-- user.hbs -->
<html lang="en">
<head>
<title>Express Node Form Validation</title>
<link href="../../public/css/bootstrap.min.css" rel="stylesheet" type="text/css">
<link href="../../public/css/styles.css" rel="stylesheet" type="text/css">
</head>
<body>
<nav class="navbar navbar-dark bg-primary">
<a class="navbar-brand" href="#">Express Form Data Validation</a>
</nav>
<div class="container">
<div class="col-md-12">
{{# if errors }}
{{# each errors }}
<p class="alert alert-danger">{{ this.msg }}</p>
{{/each}}
{{/if}}
<form method="post" action="/user/create-user">
<div class="form-group">
<label>Name</label>
<input type="text" class="form-control" name="name" />
</div>
<div class="form-group">
<label>Email</label>
<input type="text" class="form-control" name="email" />
</div>
<div class="form-group">
<label>Password</label>
<input type="password" class="form-control" name="password" />
</div>
<div class="form-group">
<label>Confirm Password</label>
<input type="password" class="form-control" name="confirm_password" />
</div>
<div class="form-group">
<button type="submit" class="btn btn-danger btn-block">Create</button>
</div>
</form>
</div>
</div>
</body>
</html>
</code></pre>
<p>👉 Code on GitHub
<a href="https://github.com/CodeCrunchies/LearningLab/tree/master/express-node-server-side-form-validation">LearningLab - Express-Node-Server-form-Validation</a></p>
<h4>Happy Coding! 💻 🤓 🌴 🐒</h4>]]></content:encoded>
</item>
<item>
<title><![CDATA[CSS Selectors CheatSheet 🤓]]></title>
<link>http://irenaapp.de//blog-css-selectors-post/</link>
<guid>http://irenaapp.de//blog-css-selectors-post/</guid>
<pubDate>Sun, 24 Jan 2021 23:14:21 GMT</pubDate>
<description><![CDATA[In CSS, selectors are patterns used to select DOM elements Here is an example of using selectors. In the following code, a and h1 are…]]></description>
<content:encoded><![CDATA[<h1>In CSS, selectors are patterns used to select DOM elements</h1>
<p>Here is an example of using selectors. In the following code, a and h1 are selectors:</p>
<pre><code class="language-CSS">a {
color: black;
}
h1 {
font-size 24px;
}
</code></pre>
<h3>common selectors</h3>
<p>head selects the element with the head tag</p>
<p><code>.red </code> - selects all elements with the ‘red’ class</p>
<p><code>#nav</code> - selects the elements with the ‘nav’ Id</p>
<p><code>div.row </code>- selects all elements with the div tag and the ‘row’ class</p>
<p><code>[aria-hidden="true"] </code>- selects all elements with the aria-hidden attribute with a value of “true”</p>
<h2>Element selectors</h2>
<p><strong>Element</strong> -- selects all <code>h2</code> elements on the page</p>
<pre><code class="language-CSS">h2 {
foo: bar;
}
</code></pre>
<p><strong>Group</strong> -- selects all <code>h1</code>, <code>h2</code> and <code>h3</code> elements on the page</p>
<pre><code class="language-CSS">h1, h2, h3 {
foo: bar;
}
</code></pre>
<h3>combination of selectors</h3>
<p><code>li</code> a DOM descendant combinator. All <code>a </code>tags that are a *<em>child</em> of <code>li</code> tags</p>
<p><code>div.row * </code> selects all elements that are descendant (or child) of the elements with div tag and ‘row’ class</p>
<p><code>li > a</code> Difference combinator. Select direct descendants, instead of all descendants like the descendant selectors</p>
<p><code>li + a</code> The adjacent combinator. It selects the element that is immediately preceded by the former element. In this case, only the first a after each li.</p>
<p><code>li, a </code> Selects all a elements and all <code>li</code> elements.</p>
<p><code>li ~ a </code>The sibling combinator. Selects a element following a <code>li</code> element.</p>
<h3>Pseudo-selectors or pseudo structural classes</h3>
<p>These are also useful for selecting structural elements from the DOM.</p>
<p>Here are some of them:</p>
<p><code>:first-child</code> - Target the first element immediately inside (or child of) another element</p>
<p><code>:last-child</code> - Target the last element immediately inside (or child of) another element</p>
<p><code>:nth-child()</code> - Target the nth element immediately inside (or child of) another element. Admits integers, <strong>even, odd, or formulas</strong></p>
<p><code>a:not(.name)</code> - Selects all a elements that are not of the .name class</p>
<p><code>::after</code> Allows inserting content onto a page from CSS, instead of HTML. While the end result is not actually in the DOM, it appears on the page as if it is. This content loads after HTML elements.</p>
<p><code>::before </code> Allows inserting content onto a page from CSS, instead of HTML. While the end result is not actually in the DOM, it appears on the page as if it is. This content loads before HTML elements.</p>
<p>👉 We can use pseudo-classes to define a special state of an element of the DOM. But they don’t point to an element by themselves .</p>
<p><code>:hover </code>- selects an element that is being hovered by a mouse pointer</p>
<p><code>:focus</code> selects an element receiving focus from the keyboard or programatialy</p>
<p><code>:active</code> selects an element being clicked by a mouse pointer</p>
<p><code>:link</code> selects all links that have not been clicked yet</p>
<p><code>:visited</code> selects a link that has already been clicked</p>
<p>The nth-child selector is a css psuedo-class taking a pattern by which to match one or more elements relative to their position among siblings.</p>
<pre><code class="language-CSS"> a:nth-child(pattern) {
/* Css goes here */
}
</code></pre>
<p>Pattern
The patterns accepted by <code>nth-child</code> can come in the form of keywords or an equation of the form An+B.</p>
<p><strong>Odd</strong></p>
<ul>
<li>Odd returns all odd elements of a given type.</li>
</ul>
<pre><code class="language-CSS"> a:nth-childe(odd) {
/* CSS goes here */
}
</code></pre>
<p><strong>Even</strong></p>
<ul>
<li>👉 Even returns all even elements of a given type.</li>
</ul>
<pre><code class="language-css"> a:nth-childe(even) {
/* CSS goes here */
}
</code></pre>
<p><strong>An+B</strong>
Returns all elements matching the equation An+B for every positive integer value of n (in addition to 0).</p>
<p>For example, the following will match every 3rd anchor element:</p>
<pre><code class="language-css"> a:nth-childe(3n) {
/* CSS goes here */
}
</code></pre>
<h2>Class and ID selectors</h2>
<p><strong>Class</strong> -- selects all elements with class attribute containing <code>foo</code> or only <code>p</code> elements with that class</p>
<pre><code class="language-CSS">.foo {
bar: fum;
}
p.foo {
bar: fum;
}
</code></pre>
<p><strong>ID</strong> -- selects the element with 'baz' id attribute value</p>
<pre><code class="language-CSS">#foo {
bar: fum;
}
</code></pre>
<h2>Contextual selectors</h2>
<p><strong>Descendant</strong> -- selects all <code>p</code> elements within the infinite-level hierarchy of element <code>#foo</code> descendants</p>
<pre><code class="language-CSS">#foo p {
bar: fum;
}
</code></pre>
<p><strong>Adjacent sibling</strong> -- selects the sibling element <code>p</code> that is immediately next to <code>h2</code> element</p>
<pre><code class="language-CSS">h2 + p {
foo: bar;
}
</code></pre>
<p><strong>Child</strong> -- selects all <code>p</code> elements that are immediate children of <code>#foo</code> element</p>
<pre><code class="language-CSS">#foo > p {
bar: fum;
}
</code></pre>
<p><strong>General sibling</strong> -- selects all elements <code>p</code> that are siblings to the <code>h2</code> element</p>
<pre><code class="language-CSS">h2 ~ p {
foo: bar;
}
</code></pre>
<h2>Pseudo-class selectors</h2>
<h3>Pseudo-class selectors for link and user states</h3>
<p><strong>Unvisited link</strong> -- applies to link elements that have not been visited</p>
<pre><code class="language-CSS">a:link {
foo: bar;
}
</code></pre>
<p><strong>Visited link</strong> -- applies to link elements that have been visited</p>
<pre><code class="language-CSS">a:visited {
foo: bar;
}
</code></pre>
<p><strong>Focus state</strong> -- applies to selected <code>.foo</code> element that is ready for input</p>
<pre><code class="language-CSS">.foo:focus {
bar: fum;
}
</code></pre>
<p><strong>Hover state</strong> -- applies when mouse pointer is over the <code>.foo</code> element</p>
<pre><code class="language-CSS">.foo:hover {
bar: fum;
}
</code></pre>
<p><strong>Active state</strong> -- applies when <code>.foo</code> element is in process of being clicked</p>
<pre><code class="language-CSS">.foo:active {
bar: fum;
}
</code></pre>
<h3>Pseudo-class selectors that apply to siblings</h3>
<p><strong>First child</strong> -- selects the specified <code>.foo</code> element when it is the first child of its parent</p>
<pre><code class="language-CSS">.foo:first-child {
bar: fum;
}
</code></pre>
<p><strong>Last child</strong> -- selects the specified <code>.foo</code> element when it is the last child of its parent</p>
<pre><code class="language-CSS">.foo:last-child {
bar: fum;
}
</code></pre>
<p><strong>Only child</strong> -- selects the specified <code>.foo</code> element when it is the only child of its parent</p>
<pre><code class="language-CSS">.foo:only-child {
bar: fum;
}
</code></pre>
<p><strong>First of type</strong> -- selects the <code>h2</code> element when it is the first element of its type within its parent element</p>
<pre><code class="language-CSS">h2:first-of-type {
foo: bar;
}
</code></pre>
<p><strong>Last of type</strong> -- selects the <code>h2</code> element when it is the last element of its type within its parent element</p>
<pre><code class="language-CSS">h2:last-of-type {
foo: bar;
}
</code></pre>
<p><strong>Only of type</strong> -- selects the <code>h2</code> element when it is the only element of its type within its parent element</p>
<pre><code class="language-CSS">h2:only-of-type {
foo: bar;
}
</code></pre>
<p><strong>Nth child</strong> -- selects the <code>n</code>th <code>.foo</code> child element</p>
<pre><code class="language-CSS">.foo:nth-child(n) {
bar: fum;
}
</code></pre>
<p><strong>Nth last child</strong> -- selects the <code>n</code>th <code>.foo</code> child element counting backwards</p>
<pre><code class="language-CSS">.foo:nth-last-child(n) {
bar: fum;
}
</code></pre>
<p><strong>Nth of type</strong> -- selects the <code>n</code>th <code>h2</code> child element of its type</p>
<pre><code class="language-CSS">h2:nth-of-type(n) {
foo: bar;
}
</code></pre>
<p><strong>Nth last of type</strong> -- selects the <code>n</code>th <code>h2</code> child element of its type counting backwards</p>
<pre><code class="language-CSS">h2:nth-last-of-type(n) {
foo: bar;
}
</code></pre>
<p>Useful <code>n</code> values:</p>
<ul>
<li>
<p><code>odd</code> or <code>2n+1</code> -- every odd child or element</p>
</li>
<li>
<p><code>even</code> or <code>2n</code> -- every even child or element</p>
</li>
<li>
<p><code>n</code> -- every nth child or element</p>
</li>
<li>
<p><code>3n</code> -- every third child or element (3, 6, 9, ...)</p>
</li>
<li>
<p><code>3n+1</code> -- every third child or element starting with <code>1</code> (1, 4, 7, ...)</p>
</li>
<li>
<p><code>n+6</code> -- all but first five children or elements (6, 7, 8, ...)</p>
</li>
<li>
<p><code>-n+5</code> -- only first five children or elements (1, 2, ..., 5)</p>
</li>
</ul>
<h3>Pseudo-element selectors</h3>
<p><strong>First letter</strong> -- selects the first letter of the specified <code>.foo</code> element, commonly used with <code>:first-child</code> to target first paragraph</p>
<pre><code class="language-CSS">.foo::first-letter {
bar: fum;
}
</code></pre>
<p><strong>First line</strong> -- selects the first line of the specified <code>.foo</code> element, commonly used with <code>:first-child</code> to target first paragraph</p>
<pre><code class="language-CSS">.foo::first-line {
bar: fum;
}
</code></pre>
<p><strong>Before</strong> -- adds generated content before the <code>.foo</code> element when used with <code>content</code> property</p>
<pre><code class="language-CSS">.foo::before {
bar: fum;
content: 'baz';
}
</code></pre>
<p><strong>After</strong> -- adds generated content after the <code>.foo</code> element when used with <code>content</code> property</p>
<pre><code class="language-CSS">.foo::after {
bar: fum;
content: 'baz';
}
</code></pre>
<h2>Attribute selectors</h2>
<p><strong>Present</strong> -- selects <code>.foo</code> elements with <code>bar</code> attribute present, regardless of its value</p>
<pre><code class="language-CSS">.foo[bar] {
fum: baz;
}
</code></pre>
<p><strong>Exact</strong> -- selects <code>.foo</code> elements where the <code>bar</code> attribute has the exact value of <code>fum</code></p>
<pre><code class="language-CSS">.foo[bar="fum"] {
baz: qux;
}
</code></pre>
<p><strong>Whitespace separated</strong> -- selects <code>.foo</code> elements with <code>bar</code> attribute values contain specified partial value of <code>fum</code> (whitespace separated)</p>
<pre><code class="language-CSS">.foo[bar~="fum"] {
baz: qux;
}
</code></pre>
<p><strong>Hyphen separated</strong> -- selects <code>.foo</code> elements with <code>bar</code> attribute values contain specified partial value of <code>fum</code> immediately followed by hyphen (<code>-</code>) character</p>
<pre><code class="language-CSS">.foo[bar|="fum"] {
baz: qux;
}
</code></pre>
<p><strong>Begins with</strong> -- selects <code>.foo</code> elements where the <code>bar</code> attribute begins with <code>fum</code></p>
<pre><code class="language-CSS">.foo[bar^="fum"] {
baz: qux;
}
</code></pre>
<p><strong>Ends with</strong> -- selects <code>.foo</code> elements where the <code>bar</code> attribute ends with <code>fum</code></p>
<pre><code class="language-CSS">.foo[bar$="fum"] {
baz: qux;
}
</code></pre>
<p><strong>Contains</strong> -- selects <code>.foo</code> elements where the <code>bar</code> attribute contains string <code>fum</code> followed and preceded by any number of other characters</p>
<pre><code class="language-CSS">.foo[bar*="fum"] {
baz: qux;
}
</code></pre>
<h2>Misc selectors</h2>
<p><strong>Not</strong> -- selects <code>.foo</code> elements that are NOT <code>.bar</code> elements</p>
<pre><code class="language-CSS">.foo:not(.bar) {
fum: baz;
}
</code></pre>
<p><strong>Root</strong> -- selects the highest level parent element in the DOM</p>
<pre><code class="language-CSS">:root {
foo: bar;
}
</code></pre>
<p><strong>Empty</strong> -- selects <code>.foo</code> elements that have no children or whitespace inside</p>
<pre><code class="language-CSS">.foo:empty {
bar: fum;
}
</code></pre>
<p><strong>In-range</strong> and <strong>Out-of-range</strong> -- selects <code>.foo</code> elements that have values in or out of range</p>
<pre><code class="language-CSS">.foo:in-range {
bar: fum;
}
.foo:out-of-range {
bar: fum;
}
</code></pre>
<p>Happy Coding!! 🤓 💻</p>]]></content:encoded>
</item>
<item>
<title><![CDATA[CSS - Selectors 🤓]]></title>
<link>http://irenaapp.de//blog-css-selectors-post/</link>
<guid>http://irenaapp.de//blog-css-selectors-post/</guid>
<pubDate>Tue, 19 Jan 2021 23:14:21 GMT</pubDate>
<description><![CDATA[Basic Selectors index.html style.css :enabled The :enabledpseudo-class in CSS selects focusable elements that are not disabled, and…]]></description>
<content:encoded><![CDATA[<pre><code class="language-css">selectorA {
property1: value1;
property2: value2;
}
selectorB {
property1: value3;
property2: value4;
}
</code></pre>
<pre><code class="language-css">selector:pseudo-class::pseudo-element {
-vendor-property: value;
}
selector[attribute],
selector ~ relation {
property: -vendor-value;
-vendor-property: -vendor-value;
-vendor-property: weirdsyntax;
}
</code></pre>
<h2>Basic Selectors</h2>
<p><code>index.html</code></p>
<pre><code class="language-html"><ul>
<li id="myID" class="myClass">item 1</li>
<li class="myClass">item 2</li>
<li>item 3</li>
</ul>
</code></pre>
<p><code>style.css</code></p>
<pre><code class="language-css">#myID
ID
.myClass
class
li
tag name
ul { font-weight: bold; }
li { color: yellow; }
.myClass { color: red; }
#myID { color: blue; }
</code></pre>
<pre><code class="language-css">
CSS Level 1 Selectors
.class
#id
E F
:link
:active
CSS Level 2 Selectors
*
E > F
E + F
E[attribute]
E[attribute=value]
E[attribute~=value]
E[attribute|=value]
:first-child
:lang(en)
:focus
:hover
:visited
:before
:after
:first-letter
:first-line
</code></pre>
<pre><code class="language-css">UI / Selectors #4
:enabled
:disabled
:checked
:default
:valid
:invalid
:in-range
:out-of-range
:required
optional
:read-only
:read-write
</code></pre>
<h2>:enabled</h2>
<p>The <code>:enabled</code>pseudo-class in CSS selects focusable elements that are not disabled, and therefore enabled. It is only associated with form elements (<code><input>, <select>, <textarea></code>). Enabled elements includes ones in that you can select, that you can enter data into, or that you can focus on or click.</p>
<p>So when a checkbox is checked, and you are targeting the label immediately after it:</p>
<pre><code class="language-css">input:enabled + label{
color: #363;
font-style: italic;
}
</code></pre>
<p>The label text will dark grey and italic if the checkbox is enabled, meaning the user can toggle it on and off.</p>
<p>:enabled should match an <code><a>, <area>, or <link> </code>with href attributes, but browsers don’t seem to handle that scenario. You can style <code><button>, <input>,<textarea></code>, <code><optgroup>, <option></code> and <code><fieldset></code>s that are not disabled. When<code><menu></code> is supported, we should also be able to target<code> <command></code> and <code><li></code>‘s that are children of <code><menu></code>, if not disabled.</p>
<p>You would also think that elements with contenteditable and tabindex attributes would be selectable with the :enabled pseudoclass.</p>
<h2>Structural selectors</h2>
<pre><code class="language-css">:root
:empty
:blank
:nth-child()
:nth-last-child()
:first-child*
:last-child
:only-child
:nth-of-type()
:nth-last-of-type()
:first-of-type
:last-of-type
:only-of-type
</code></pre>
<p>👉 Target elements on the page based on their relationships to other elements in the DOM.
👉 Updates dynamically if page updates.
👉 Reduced need for extra markup, classes and IDs - CSS2 / IE8</p>]]></content:encoded>
</item>
<item>
<title><![CDATA[Express - Dynamic Views 🤓]]></title>
<link>http://irenaapp.de//blog-express-dynamic-views-post/</link>
<guid>http://irenaapp.de//blog-express-dynamic-views-post/</guid>
<pubDate>Mon, 18 Jan 2021 23:14:21 GMT</pubDate>
<description><![CDATA[ExpressJS - the differences Static vs Dynamic page The learning Goals of this article are as follows: create views in Express understanding…]]></description>
<content:encoded><![CDATA[<h2>ExpressJS - the differences Static vs Dynamic page</h2>
<p>The learning Goals of this article are as follows:</p>
<ul>
<li>
<p>create <strong>views</strong> in Express</p>
</li>
<li>
<p>understanding the role of the <strong>dynamic templates</strong> and why we use them</p>
</li>
<li>
<p>understanding and use <strong>HandlebarJS</strong> for creating dynamic templates</p>
</li>
<li>
<p>use <strong>if</strong>, <strong>with</strong>, and <strong>each</strong> block helpers</p>
</li>
</ul>
<p>One thing that can get confusing when trying to figure out what goes where is the whole Static and Dynamic pages and what exactly each of them mean and do. Static files are usually found in the /public directory which will contain the client side JavaScript, CSS files, and images. When you see those files you may think how are those static when they are technically doing something.</p>
<p>That is true but compared to other parts of the <strong>Models Views Controller (MVC)</strong> architecture they don’t have a lot of operations going on. To set this up we will have to make sure the code knows where to look when needing to retrieve code from the public directory. First you’ll want to make sure you have required Express with:</p>
<pre><code class="language-js">var express = require('express');
</code></pre>
<p>Once you have Express required along with any others that need to be required you can move on to your public directory like:</p>
<pre><code class="language-js">app.use(express.static(path.join(__dirname, 'public')));
</code></pre>
<p>Another part of the static portion is the Views of the MVC architecture which has some HTML on the server side. It again is considered static because there isn’t any data being processed in that file. It however does accept forms and allows users to input their data which then goes into a more dynamic file which is usually the models directory.</p>
<p>👉 When we signaled that we were going dynamic it meant there was going to be a lot of moving pieces and this is where things can go wrong quickly.</p>
<p>👉 <strong>The dynamic part allows us to have separate files to access different data and route it to where it needs to be.</strong></p>
<pre><code class="language-js">const routes = require('./routes/index');
app.use('/', routes);
</code></pre>
<p>👉 This points us towards our routes directory which is a js file that now has code in it that is doing something similar to the <code>app.js</code> file. Which we have to require code in here as well:</p>
<pre><code class="language-js">const express = require('express');
const router = express.Router();
const Product = require('../models/product');
</code></pre>
<p>The last line which is directing us to the models directory. The models directory is for the most part where we are storing the data until we need to use any of it. The <strong>routes</strong> file has some functions in it which again makes it dynamic as it is getting data and directing it to another location. That piece of code looks like:</p>
<pre><code class="language-js">router.post('/cart', function(req, res, next) {
let temp = parseInt(req.body.id);
let product = Product.find(temp);
req.session.cart.push(product);
res.redirect('/');
});
</code></pre>
<p>To show that this is dynamic this code is parsing into another data structure and then finding that piece of data needed. It then is pushing that data into another file which is being posted possibly to a static file and then you are being redirected to the index file</p>
<h2>Let's brake it even more simple:</h2>
<p>👉 ExpressJS can send text to the browser with just a few lines of code:</p>
<pre><code class="language-jsx">const express = require('express');
const app = express();
app.get('/', (req, res, next) => {
response.send('hello world');
});
app.listen(3000);
</code></pre>
<p>🤓 🔨👉 We can also send more complex HTML to the browser:</p>
<p>We refer to the arguments in our route’s callback as</p>
<pre><code class="language-js">request
</code></pre>
<p>and</p>
<pre><code class="language-js">response
</code></pre>
<p>as a demonstration.</p>
<p>These are represented commonly as <code>req</code> and <code>res</code> in the documentation, so we’ll use that going forward.</p>
<pre><code class="language-js">app.get('/hello', (req, res, next) => {
res.send(`
<!doctype html>
<html>
<head>
<link rel="stylesheet" href="stylesheets/style.css">
</head>
<body>
This is my second route
</body>
</html>
`);
});
</code></pre>
<p>This way would be tedious and complicated as our application grows. Can you imagine our <code>app.js</code> having thousands of lines? There must be a better way!</p>
<p>In ExpressJS <em>and most frameworks-</em> you can create files specifically for our HTML. This way, we can keep the HTML separated from the logic of our application.</p>
<p>These files will be called <strong>views</strong>, and once we learn how to use them, we can simply call <code>res.render</code> instead of <code>res.send</code> and send an HTML file to the browser:</p>
<pre><code class="language-js">app.get('/', (req, res, next) => {
res.render('index.html');
});
</code></pre>
<h2><strong>Dynamic Views</strong></h2>
<p>Views are templates for specifically HTML. HTML is what the client will see in their browser.</p>
<p>To start using views, we should create a folder inside of our project called <code>views</code> to group them. We will create our first view <code>index.hbs</code>:</p>
<pre><code class="language-bash">$ mkdir views
$ touch views/index.hbs
$ tree .
.
├── app.js
├── package.json
├── stylesheets
│ └── style.css
└── views
└── index.hbs
</code></pre>
<p>Notice we use a new extension</p>
<p><strong>.hbs</strong></p>
<p>instead of</p>
<p><strong>.html</strong></p>
<p>The advantage of separating views is that we separate the ExpressJS server logic (routes, server setup, server start, etc.) and the presentation (HTML), making our code more manageable and well structured.</p>
<p>ExpressJS won’t know by itself where we decided to group our views, but there is an easy fix. We can tell our Express app where to look for our views:</p>
<pre><code class="language-jsx">// creates an absolute path pointing to a folder called "views"
app.set('views', __dirname + '/views');
</code></pre>
<p>In Express, instead of using plain HTML, we can use a fancier version of HTML: <strong><code>hbs</code></strong>, or <strong><a href="http://handlebarsjs.com/">Handlebars</a></strong>.</p>
<p>We’ll get into more detail shortly about <strong>HBS</strong>, but for now, make sure you install it in our app:</p>
<pre><code class="language-bash">$ npm install hbs
</code></pre>
<p>… And tell our Express app that <strong>HBS</strong> will be in charge of rendering the HTML:</p>
<pre><code class="language-jsx">app.set('views', __dirname + '/views');
app.set('view engine', 'hbs');
</code></pre>
<p>Open the <code>views/index.hbs</code> file and add some content:</p>
<pre><code class="language-jsx"><!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>My first view</title>
<link rel="stylesheet" href="stylesheets/style.css">
</head>
<body>
<h1>If you can dream it, you can code it!</h1>
<img src="https://media.giphy.com/media/l0MYEqEzwMWFCg8rm/giphy.gif">
</body>
</html>
</code></pre>
<p>Finally, instead of <code>res.send()</code>. we have to tell Express to send and render our <code>index</code> view to the client:</p>
<pre><code class="language-jsx">app.get('/', (req, res, next) => {
// send views/index.hbs for displaying in the browser
res.render('index');
});
</code></pre>
<p>When we visit <code>localhost:3000</code>, we’ll see our HTML rendered!</p>
<p><strong>Let's Practice</strong></p>
<p>👉 Create a new route called <code>about</code>:</p>
<ul>
<li>It should render a separate view also called <code>about.hbs</code></li>
<li>Create an <code>h1</code> with your name</li>
<li>Add a giphy image that you like</li>
</ul>
<h2><strong>Handlebars</strong></h2>
<p>As we saw in the previous example, our file had a <code>.hbs</code> extension. This extension stands for <em>Handlebars</em>. <strong><a href="http://handlebarsjs.com/">Handlebars.js</a></strong> is a sweet javascript library for building clean logicless templates based on the <strong><a href="https://mustache.github.io/">Mustache Templating Language</a></strong>.</p>
<p>One of the essential features of using <strong>Handlebars</strong> is that we can make templates dynamic by sending information to them and using that data to render our web app.</p>
<p>The <code>res.render()</code> method can take an additional parameter that will contain a JavaScript object with information we can use in the view.</p>
<p>Let’s look at an example:</p>
<pre><code class="language-js">// app.js
app.get('/', (req, res, next) => {
let data = {
name: "Irene",
techblog: "Irene WebDev"
};
res.render('index', data);
});
</code></pre>
<pre><code class="language-html"><!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Home</title>
</head>
<body>
<h1>Hello {{name}}!</h1>
<p>Welcome to my {{techblog}}!!</p>
</body>
</html>
</code></pre>
<p>Any key passed in the object will be available in the view, with a variable of the same name.</p>
<p><strong><code>{{ variableName }}</code></strong> signifies that a variable will be output to the HTML we send to the client</p>
<p>Templates are mostly HTML, but <code>HBS</code> will analyze them and execute JavaScript before it renders the final HTML and sends it to the browser:</p>
<h2><strong>Handlebars - Scaping HTML</strong></h2>
<p>By default Handlebars escapes HTML values included in a expression with the <code>{{ }}</code>. That means if we send data like this:</p>
<pre><code class="language-js">app.get('/', (req, res, next) => {
let data = {
name: "Irene",
techblog: "<span>Irene WebDev</span>"
};
res.render('index', data);
});
</code></pre>
<p>And then print it on our <code>HBS</code> file:</p>
<pre><code class="language-html"><!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Home</title>
</head>
<body>
<h1>Hello {{name}}!</h1>
<p>Welcome to my {{techblog}}!!</p>
</body>
</html>
</code></pre>
<p>If we don’t want Handlebars to escape a value, we should use the triple-stash: <strong><code>{{{ }}}</code></strong>.</p>
<pre><code class="language-js"><!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Home</title>
</head>
<body>
<h1>Hello {{name}}!</h1>
<p>Welcome to my {{{techblog}}}!!</p>
</body>
</html>
</code></pre>
<h2>🛑 <strong>Built-In Helpers</strong></h2>
<p>Besides the dynamic template feature, Handlebars give us some great helpers to make our life easier when coding our web!</p>
<h3><strong>The <code>if</code> block helper</strong></h3>
<p>You can use the <code>if</code> helper to render a block conditionally. That means, if its argument returns <code>false</code>, <code>undefined</code>, <code>null</code>, <code>""</code>, <code>0</code>, or <code>[]</code>, <strong>Handlebars</strong> will not render the block.</p>
<pre><code class="language-js">app.get('/', (req, res, next) => {
let data = {
name: "Irene",
};
res.render('index', data);
});
</code></pre>
<pre><code class="language-html"><h1>Hello {{name}}!</h1>
{{#if lastName}}
<h2>This won't be displayed!!</h2>
{{/if}}
</code></pre>
<p>Since <code>lastName</code> is <code>undefined</code>, our <code><h2></code> tag will not be displayed! Now, let’s add the <code>lastName</code> property to the data!</p>
<pre><code class="language-js">app.get('/', (req, res, next) => {
let data = {
name: "Irene",
lastName: "Popova"
};
res.render('index', data);
});
</code></pre>
<pre><code class="language-html"><h1>Hello {{name}} {{lastName}}!</h1>
{{#if lastName}}
<h2>This will be displayed!!</h2>
{{/if}}
</code></pre>
<p>We can also add an <code>else</code> statement, which makes this even more powerful!</p>
<pre><code class="language-html"><h1>Hello {{name}} {{lastName}}!</h1>
{{#if address}}
<h2>This won't be displayed!!</h2>
{{else}}
<h2>This will be displayed because the "address" property does not exists!!</h2>
{{/if}}
</code></pre>
<h3>🛑 <strong>The <code>unless</code> block helper</strong> 🤔</h3>
<p>You can use the <code>unless</code> helper as the inverse of the <code>if</code> helper. It will render the block if the expression returns a <strong>falsy value</strong>.</p>
<pre><code class="language-js"><h1>Hello {{name}} {{lastName}}!</h1>
{{#unless address}}
<h3>WARNING: We cannot find this address!</h3>
{{/unless}}
</code></pre>
<p>If looking up <code>address</code> under the current context returns a <strong>falsy value</strong>, Handlebars will render the warning. Otherwise, it will render nothing. In our example, it will render the WARNING.</p>
<p>If we add the <code>address</code> property, then the warning should disappear!</p>
<pre><code class="language-js">app.get('/', (req, res, next) => {
let data = {
name: "Irene",
lastName: "Popova",
address: "Sherlock str"
};
res.render('index', data);
});
</code></pre>
<h3>🛑 <strong>The <code>each</code> block helper</strong></h3>
<p>The <code>each</code> block helps us to iterate over a list of elements, mainly <code>objects</code> and <code>array</code>. Imagine printing a list of cities. We can do something like this:</p>
<pre><code class="language-html"><ul>
<li>Berlin</li>
<li>London</li>
<li>Athena</li>
<li>Munich</li>
<li>Sofia</li>
</ul>
</code></pre>
<p>We are repeating the same <code><li></code> tag six times, only changing the content inside the tags. Using the <code>each</code> block, we can do the following:</p>
<p>First, we need to pass the data to our view:</p>
<pre><code class="language-js">app.get('/', (req, res, next) => {
let data = {
name: "Irene",
lastName: "Popova",
address: "Sherlock Str.",
cities: ["Berlin", "London", "Athena", "Munich", "Sofia"]
};
res.render('index', data);
});
</code></pre>
<p>Once we have the data on our <code>index.hbs</code> file:</p>
<pre><code class="language-js"><ul>
{{#each cities}}
<li>{{this}}</li>
{{/each}}
</ul>
</code></pre>
<blockquote>
<p>Inside the block, you can use 👇</p>
</blockquote>
<pre><code>this
</code></pre>
<p>to reference the element we are iterating.</p>
<p>You can optionally provide an <code>{{else}}</code> section which will display only when the list is empty.</p>
<pre><code class="language-html"><ul>
{{#each cities}}
<li>{{this}}</li>
{{else}}
<p>No cities found yet!</p>
{{/each}}
</ul>
</code></pre>
<h3>🛑 <strong><code>@index</code></strong></h3>
<p>When looping through items in <code>each</code>, you can optionally reference the current loop <strong>index</strong> via <code>{{@index}}</code></p>
<pre><code class="language-html"><ul>
{{#each cities}}
<li>{{@index}}: {{this}}</li>
{{/each}}
</ul>
</code></pre>
<h3>🛑 <strong><code>@key</code></strong></h3>
<p>Additionally for <code>object</code> iteration, <code>{{@key}}</code> references the current key name:</p>
<pre><code class="language-js">{{#each object}}
{{@key}}: {{this}}
{{/each}}
</code></pre>
<h3>🛑 <strong><code>@first</code> - <code>@last</code></strong></h3>
<p>The first and last steps of iteration are noted via the <code>@first</code> and <code>@last</code> variables when iterating over an array.</p>
<pre><code class="language-html"><ul>
{{#each cities}}
{{#if @first}}
<li><b>{{this}}</b></li>
{{else if @last}}
<li><i>{{this}}</i></li>
{{else}}
<li>{{this}}</li>
{{/if}}
{{/each}}
</ul>
</code></pre>
<p>It is important to notice that the <code>@first</code> and <code>@last</code> helpers return a boolean! When iterating over an object, only the @first is available.</p>
<h3>🛑 <strong>The <code>with</code> block helper</strong></h3>
<p>Commonly, Handlebars evaluates its templates against the context passed into the compiled method. We can shift that context to a section of a template by using the built-in <code>with</code> block helper.</p>
<p>For example, passing the following data:</p>
<pre><code class="language-js">app.get('/', (req, res, next) => {
let data = {
name: "Irene",
lastName: "Popova",
address: {
street: "Sherlock str.",
number: 66
},
cities: ["Berlin", "London", "Athena", "Munich", "Sofia"]
};
res.render('index', data);
});
</code></pre>
<p>We can do the following: 👇</p>
<pre><code class="language-html"><h1>Hello {{name}} {{lastName}}!</h1>
{{#with address}}
<p>{{street}}, {{number}}</p>
{{/with}}
</code></pre>
<p>Using the <code>with</code> helper, we shift the context inside it, so we can refeer to <code>{{address.street}}</code> and <code>{{address.number}}</code>, as <code>{{street}}</code> and <code>{{number}}</code>.</p>
<h2><strong>Let's summarize</strong></h2>
<p>In this article, I gave you a brief introduction about templating with <code>hbs</code>.</p>
<p>⚠️ Ideally, you want to have as little logic as possible in your <strong>views</strong>, but using <code>loops</code> and the occasional <code>if</code> statement allows you to harness the real power of using a backend framework.</p>
<p>So dynamic means there is a lot happening in a short amount of time and if something is not functioning properly or defined properly other parts of the code will not function either. Whereas the static pages will still display something but it will not be showing the correct data if the dynamic pages are not operating as they should.</p>
<h2><strong>Extra Resources</strong></h2>
<ul>
<li><a href="http://handlebarsjs.com/">HandlebarsJS documentation</a></li>
<li><a href="https://expressjs.com/en/guide/routing.html">ExpressJS Routing documentation</a></li>
<li><a href="https://www.npmjs.com/package/express">Express npmjs</a></li>
<li><a href="https://github.com/expressjs/generator">Express generator</a></li>
</ul>
<p><strong>Happy Coding!</strong> 🤓 :</p>]]></content:encoded>
</item>
<item>
<title><![CDATA[CSS - How to use z-index property 🚀]]></title>
<link>http://irenaapp.de//blog-css-z-index-post/</link>
<guid>http://irenaapp.de//blog-css-z-index-post/</guid>
<pubDate>Mon, 11 Jan 2021 23:14:21 GMT</pubDate>
<description><![CDATA[The hassle around the Z-index Z-Index is one of the most confusing and unintuitive properties in CSS, but it’s actually pretty simple once…]]></description>
<content:encoded><![CDATA[<h2>The hassle around the Z-index</h2>
<p>Z-Index is one of the most confusing and unintuitive properties in CSS, but it’s actually pretty simple once you understand it.
Your first instinct is probably to think that you can just set z-index on any element and that that alone is going to determine its stacking order. This is WRONG.
👉 The z-index property is used to control the Z axis positioning of elements.</p>
<p>It’s very useful when you have multiple elements that overlap each other, and you need to decide which one is visible, as nearer to the user, and which one(s) should be hidden behind it.</p>
<p>👉 This property takes a number (without decimals) and uses that number to calculate which elements appear nearer to the user, in the Z axis.</p>
<p>The higher the z-index value, the more an element is positioned nearer to the user.</p>
<h2>🛑 Z-index only applies to positioned elements.</h2>
<p>A positioned element is an element who’s position property is NOT static (eg. relative, absolute, fixed). Setting a z-index on an unpositioned element does nothing.
If a positioned element has a z-index of X, then all of its children will also be stuck with a z-value of X</p>
<p>You can change the z-index of any child elements all you want, but that won’t do anything!
(Note: z-value is not an actual CSS term. I only use it because z-index technically defaults to “auto” and can be set to whatever you want, even if it does nothing)</p>
<pre><code class="language-html"><div id="parent" style="position: relative; z-index: 6;">
<div id="child" style="position: relative: z-index: 7;">
<div id="grandchild" style="position: relative; z-index: 9;" >
</div>
</div>
</div>
</code></pre>
<p>The <strong><code>z-value</code></strong> of each of these elements is 6, and there’s no way to change that without modifying the z-index of #parent.
In technical terms, a stacking context is formed when a positioned element has a <code>z-index</code>.</p>
<p>👉 A stacking context is a single atomic unit composed of a parent along with its children. All elements within a stacking context are bound to the z-value set by the non-root parent (in the code box above #parent).</p>
<p>(Non-root just means that it’s not the <code><html></code> tag. The root <code><html></code> tag technically forms a stacking context, but any z-index on it is meaningless.)`</p>
<p>you can create stacking contexts within stacking contexts, but all child stacking contexts will be bound to the z-value of the outermost (non-root) stacking context.</p>
<p>In the example above, three stacking contexts are formed, and they’re nested. The z-value of all three contexts is bound to the z-index of #parent, which is 6.</p>
<p>Stacking Contexts:</p>
<pre><code class="language-html">#parent (z-value: 6)
#child
#grandchild
</code></pre>
<p>👉 Setting the <code>z-index</code> on a positioned element is only one of many ways to create a stacking context. There are various CSS properties that automatically create a stacking context on an element, regardless of whether or not a z-index is set.`</p>
<p>The full list is here, but here are some common properties that automatically create new stacking contexts:</p>
<p>👉 position: fixed</p>
<p>👉 elements with a transform value other than "none"</p>
<p>👉 elements with an opacity value less than 1.</p>
<p>So any element with position: fixed or transform: translateY(50%) is going to form a new stacking context regardless of whether a z-index has been set on that element.</p>
<p>When deciding which element should be visible and which one should be positioned behind it, the browser does a calculation on the z-index value.</p>
<p>The default value is auto, a special keyword. Using auto, the Z axis order is determined by the position of the HTML element in the page - the last sibling appears first, as it’s defined last.</p>
<p>By default elements have the static value for the position property. In this case, the z-index property does not make any difference - it must be set to absolute, relative or fixed to work.</p>
<pre><code class="language-css">.my-first-div {
position: absolute;
top: 0;
left: 0;
width: 600px;
height: 600px;
z-index: 10;
}
.my-second-div {
position: absolute;
top: 0;
left: 0;
width: 500px;
height: 500px;
z-index: 20;
}
</code></pre>
<p>The element with class .my-second-div will be displayed, and behind it .my-first-div.</p>
<p>👉 Actually any number can be used. Negative numbers too. It’s common to pick non-consecutive numbers, so you can position elements in the middle. If you use consecutive numbers instead, you would need to re-calculate the z-index of each element involved in the positioning.</p>]]></content:encoded>
</item>
<item>
<title><![CDATA[What is props drilling in React 🤖]]></title>
<link>http://irenaapp.de//blog-what-is-props-drilling/</link>
<guid>http://irenaapp.de//blog-what-is-props-drilling/</guid>
<pubDate>Mon, 11 Jan 2021 23:14:21 GMT</pubDate>
<description><![CDATA[Props drilling 🤔 Everything runs on a different thread except our code.
We need to share data with different components when working with…]]></description>
<content:encoded><![CDATA[<h3>Props drilling 🤔</h3>
<p>Everything runs on a different thread except our code.
We need to share data with different components when working with React.
But before I drill deeper, lets first make clear what are props and state.
Understanding what props and state are and the differences between them is a big step towards learning React.</p>
<h3>What are props?</h3>
<p>Props is short for properties and they are used to pass data between React components. React’s data flow between components is uni-directional (from parent to child only).</p>
<p>👉 props data can include numbers, strings, functions, objects, arrays, etc. — to a component when you call on that component. If you have multiple components, you can pass data from one component to another.</p>
<p>To pass props between components, you would add them when the component is called, just as you would pass arguments when calling on a regular JavaScript function.</p>
<h3>How do you pass data with props?</h3>
<pre><code class="language-js">
class ParentComponent extends Component {
render() {
return (
<ChildComponent name="First Child" />
);
}
}
const ChildComponent = (props) => {
return <p>{props.name}</p>;
};
</code></pre>
<p>This can be achieved in the most basic way using prop drilling. Prop drilling allows for unidirectional data sharing between components. The data passed or shared in the form of props.</p>
<p>Firstly, we need to define/get some data from the parent component and assign it to a child component’s “prop” attribute.</p>
<pre><code class="language-js"><ChildComponent name="First Child" />
</code></pre>
<p>“Name” is a defined prop here and contains text data. Then we can pass data with props like we’re giving an argument to a function:</p>
<pre><code class="language-js">const ChildComponent = (props) => {
// statements
};
</code></pre>
<p>And finally, we use dot notation to access the prop data and render it:</p>
<pre><code class="language-js">return <p>{props.name}</p>;
</code></pre>
<h3>What is state?</h3>
<p>React has another special built-in object called state, which allows components to create and manage their own data. So unlike props, components cannot pass data with state, but they can create and manage it internally.</p>
<pre><code class="language-js">class Lesson extends React.Component {
constructor() {
this.state = {
id: 1,
name: "lesson"
};
}
render() {
return (
<div>
<p>{this.state.id}</p>
<p>{this.state.name}</p>
</div>
);
}
}
</code></pre>
<h3>How to update a component’s state?</h3>
<p>State should not be modified directly, but it can be modified with a special method called <code>setState( )</code>.</p>
<pre><code class="language-js">this.state.id = “2020”; // wrong
this.setState({ // correct
id: "2020"
});
</code></pre>
<h3>What happens when state changes?</h3>
<p>why we use <code>setState( )</code>? Why do we even need the state object itself? If you’re asking these questions, don't worry – you’ll understand state soon :) Let me answer.</p>
<p>👉 A change in the state happens based on <strong>user-input</strong>, <strong>triggering an event</strong>, and so on. Also, <strong>React components (with state) are rendered based on the data in the state. State holds the initial information.</strong></p>
<p>👉 So when state changes, React gets informed and <strong>immediately re-renders the DOM</strong> – not the whole DOM, but <strong>only the component with the updated state.</strong> This is one of the reasons why React is fast.</p>
<p>And how does React get notified? 👉 with <code>setState( )</code>. <code>**The </code>setState( )` method triggers the re-rendering process for the updated parts.** React gets informed, knows which part(s) to change, and does it quickly without re-rendering the whole DOM.</p>
<p>🛑 There are 2 important points we need to pay attention to when using state:</p>
<p>👉 State shouldn’t be modified directly – the <code>setState( )</code> should be used
👉 State affects the performance of the app, and therefore it shouldn’t be used unnecessarily</p>
<h3>Can state be used in every component? 🤔</h3>
<p>A question about state is where exactly we can use it. Earlier, state could only be used in class components, not in <strong>functional components</strong>.</p>
<p>That’s why <strong>functional components were also known as stateless components</strong>. However, after the introduction of React Hooks, <strong>state can now be used both in class and functional components</strong>.</p>
<p>But if you are not using React Hooks, then you can only use state in class components.</p>
<h3>The main differences between props & state are:</h3>
<p>👉 Components receive data from outside with props, whereas they can create and manage their own data with state,</p>
<p>👉 Props are used to pass data, whereas state is for managing data</p>
<p>👉 Data from props is read-only, and cannot be modified by a component that is receiving it from outside</p>
<p>👉 State data can be modified by its own component, but is private (cannot be accessed from outside)</p>
<p>👉 Props can only be passed from parent component to child (unidirectional flow)
Modifying state should happen with the <code>setState ( )</code> method</p>
<h3>How to share data with different components ? 🤔</h3>
<p>This can be achieved in the most basic way using prop drilling. Prop drilling allows for <strong>unidirectional data sharing between components</strong>.
👉 <strong>The data passed or shared in the form of props.</strong></p>
<p>Props are the data we pass or can access, from the top-level components to any number of child components on our website.</p>
<p>👉 Props drilling (threading) refers to the process of passing data from the parent component to the exact _child component. _But, <em>in between, other components owning the props just to pass it down the chain.</em></p>
<pre><code class="language-js">
class One extends React.Component {
componentDidMount(){
console.log(One is mounted);
}
render(){
<>
return <Two/>
<Three/>
</>
);
}
}
class Two extends React.Component {
componentDidMount(){
console.log(Two is mounted);
}
render(){
return <>
</>
}
}
class Three extends React.Component {
componentDidMount(){
console.log(Three is mounted);
}
render(){
<>
return
<>
</>
);
}
}
</code></pre>]]></content:encoded>
</item>
<item>
<title><![CDATA[CSS - How to animate 🚀]]></title>
<link>http://irenaapp.de//blog-css-animations-post/</link>
<guid>http://irenaapp.de//blog-css-animations-post/</guid>
<pubDate>Mon, 11 Jan 2021 23:14:21 GMT</pubDate>
<description><![CDATA[How to bring life in a webpage ? 🤔 “Animation is about creating the illusion of life.” Brad Bird By animating information onto the page, we…]]></description>
<content:encoded><![CDATA[<h2>How to bring life in a webpage ? 🤔</h2>
<blockquote>
<p>“Animation is about creating the illusion of life.” Brad Bird</p>
</blockquote>
<p>By animating information onto the page, we give our viewers an extra piece of information that might otherwise be missing. The animation both draws attention to the new content being added and gives context to that new information.</p>
<p>Animation can convey information efficiently, or it can be used to grab attention but in the end it is all about communication.</p>
<p>Movement in our designs gives us a more powerful way to communicate. It transcends verbal and written language.</p>
<p>Subtle and appropriate animation can add appeal to our designs and credibility to our work. This happens because as humans we’re used to seeing movement all the time in the “real” world. Bringing some of that life into our work brings the two closer.</p>
<p>Animation brings us two main benefits: conveying information and grabbing attention. We can come up with many ways these benefits can help us as we build for the web.
Animation properties
<a href="https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_animated_properties">Animatable properties</a></p>
<h4>CSS ANIMATIONS in ACTION</h4>
<p>CSS animations provide even finer control over the intermediate steps between an animation, using <code>waypoints</code>. Waypoints (or <code>@keyframes</code>) are <strong>pinned points in time</strong>, during the animation, when we apply certain styles to an element. We then use the defined <strong><code>@keyframes</code></strong> to lay out what the animation should look like.</p>
<p>Suppose we want an element to animate as a bounce. The element needs to move up, move back to the original position, move back up a little, and then move back to the original position. Using keyframes, we can break down that elastic effect into percentages of time that the animation will take....</p>
<p>👉 <strong>An animation is applied to an element using the animation property.</strong></p>
<pre><code class="language-css">.container {
animation: rotate 10s linear infinite;
}
</code></pre>
<p><strong>rotate</strong> is the name of the animation, which we need to define separately. We also tell CSS to make the animation last 10 seconds, perform it in a linear way (no acceleration or any difference in its speed) and to repeat it infinitely.</p>
<p>You must define how your animation works using <strong>@keyframes</strong>. Example of an animation that rotates an item:`</p>
<pre><code class="language-css">@keyframes rotate {
0% {
transform: rotateZ(0);
}
100% {
transform: rotateZ(360deg);
}
}
</code></pre>
<p>👉 Inside the @keyframes definition you can have as many intermediate waypoints as you want.</p>
<p>👉 CSS will make the transform property to rotate the Z axis from 0 to 360 grades, completing the full loop.</p>
<p>👉 You can use any CSS transform here.</p>
<p>Notice how this does not dictate anything about the temporal interval the animation should take. This is defined when you use it via animation.</p>
<p>A CSS Animations Example</p>
<h3>Transitions</h3>
<p>CSS transitions provide a way to control how fast a change in CSS property is applied to an element. Instead of applying a style immediately (without transitions), it could be applied gradually over a defined acceleration curve using customization rules. An example would be changing a background color from black to white over a period of time.</p>
<pre><code class="language-css">transition-property: background-color;
transition-duration: 3s;
</code></pre>
<p>With this rule on the element, the background color would take three seconds to change, gradually changing from black to white, going through shades of gray. This can further be customized by adding transition-timing-function, to calculate intermediate values, and transition-delay, to delay the start of the animation.</p>
<p>CSS transitions are good for simple interactions, such as changing the background color or moving an element to a new location.</p>
<p>Browsers used to be much more simple. It wasn’t so long ago that they couldn’t render images or handle more than a handful of fonts. Then CSS gave us power over how web pages look and feel.</p>
<p>Animation in browsers isn’t new. Flash, Canvas and other JavaScript options have given us ways to animate but recently CSS has become a viable option.</p>
<h3>Transitions</h3>
<h2>The CSS animation properties</h2>
<p>CSS animations offers a lot of different parameters:</p>
<p>👉 Properties</p>
<p><strong><code>animation-name</code></strong> - the name of the animation, it references an animation created using @keyframes</p>
<p><strong><code>animation-duration</code></strong> - how long the animation should last, in seconds</p>
<p><strong><code>animation-timing-function</code></strong> - the timing function used by the animation (common values: linear, ease). Default: ease</p>
<p><strong><code>animation-delay</code></strong> - optional number of seconds to wait before starting the animation</p>
<p><strong><code>animation-iteration-count</code></strong> - how many times the animation should be performed. Expects a number, or infinite. Default: 1</p>
<p><strong><code>animation-direction</code></strong> the direction of the animation. Can be normal, reverse, alternate or alternate-reverse. In the last 2, it alternates going forward and then backwards</p>
<p><strong><code>animation-fill-mode</code></strong> - defines how to style the element when the animation ends, after it finishes its iteration count number. none or backwards go back to the first keyframe styles. forwards and both use the style that’s set in the last keyframe</p>
<p><strong><code>animation-play-state</code></strong> if set to paused, it pauses the animation. Default is running</p>
<p>The animation property is a shorthand for all these properties, in this order:</p>
<pre><code class="language-css">.container {
animation: name duration timing-function delay iteration-count direction
fill-mode play-state;
}
</code></pre>
<p>This is the example we used above:</p>
<pre><code class="language-css">.container {
animation: spin 10s linear infinite;
}`
</code></pre>
<p>####JavaScript events for CSS Animations
with JavaScript you can listen for the following events:</p>
<ul>
<li>
<p><strong>animationstart</strong></p>
</li>
<li>
<p><strong>animationend</strong></p>
</li>
<li>
<p><strong>animationiteration</strong></p>
</li>
</ul>
<blockquote>
<p>🛑 Be careful with <strong>animationstart</strong>, because if the animation starts on page load, your JavaScript code is always executed after the CSS has been processed, so the animation is already started and you cannot intercept the event.</p>
</blockquote>
<p>👇 in the index.js or whatever the name of your file</p>
<pre><code class="language-js">const container = document.querySelector('.container')
container.addEventListener(
'animationstart',
(e) => {
//do something
},
false
)
container.addEventListener(
'animationend',
(e) => {
//do something
},
false
)
container.addEventListener(
'animationiteration',
(e) => {
//do something
},
false
)
</code></pre>]]></content:encoded>
</item>
<item>
<title><![CDATA[CSS - Working with the BoxModel 🤖]]></title>
<link>http://irenaapp.de//blog-css-box-model-post/</link>
<guid>http://irenaapp.de//blog-css-box-model-post/</guid>
<pubDate>Sun, 10 Jan 2021 23:14:21 GMT</pubDate>
<description><![CDATA[How the Box Model Works Every element is a rectangular box, and there are several properties that determine the size of that box. The core…]]></description>
<content:encoded><![CDATA[<h2>How the Box Model Works</h2>
<p>Every element is a rectangular box, and there are several properties that determine the size of that box. The core of the box is defined by the width and height of an element, which may be determined by the display property, by the contents of the element, or by specified width and height properties. padding and then border expand the dimensions of the box outward from the element’s width and height. Lastly, any margin we have specified will follow the border.</p>
<p>Each part of the box model corresponds to a CSS property: width, height, padding, border, and margin.</p>
<p>Let’s look these properties inside some code:</p>
<pre><code class="language-css">div {
border: 6px solid #949599;
height: 100px;
margin: 20px;
padding: 20px;
width: 400px;
}
</code></pre>
<p>According to the box model, the total width of an element can be calculated using the following formula:</p>
<pre><code class="language-css">margin-right + border-right + padding-right + width + padding-left + border-left + margin-left
</code></pre>
<p>In comparison, according to the box model, the total height of an element can be calculated using the following formula:</p>
<pre><code class="language-css">margin-top + border-top + padding-top + height + padding-bottom + border-bottom + margin-bottom
</code></pre>]]></content:encoded>
</item>
<item>
<title><![CDATA[Manage state with useReducer Hook 🤔]]></title>
<link>http://irenaapp.de//blog-react-post-redux/</link>
<guid>http://irenaapp.de//blog-react-post-redux/</guid>
<pubDate>Sun, 29 Nov 2020 23:14:21 GMT</pubDate>
<description><![CDATA[Managing State with useReducer useReducer Hook An alternative to useState. Accepts a reducer of type (state, action) => newState, and…]]></description>
<content:encoded><![CDATA[<h3>Managing State with useReducer</h3>
<p><a href="https://reactjs.org/docs/hooks-reference.html#additional-hooks">useReducer Hook</a></p>
<p>An alternative to useState. Accepts a reducer of type (state, action) => newState, and returns the current state paired with a dispatch method. (If you’re familiar with Redux, you already know how this works.)</p>
<p>Although <code>useState</code> is a Basic Hook and useReducer is an Additional Hook, useState is actually implemented with useReducer. This means useReducer is primitive and you can use useReducer for everything you can do with useState. Reducer is so powerful that it can apply for various use cases.
The rest of this tutorial consists of various examples. Each example shows a certain use case and we show working code.
Example01: Minimal pattern
Let’s look at the simplest example code. We mostly use the counter example throughout this tutorial.</p>
<pre><code class="language-js">const initialState = 0
const reducer = (state, action) => {
switch (action) {
case 'increment':
return state + 1
case 'decrement':
return state - 1
case 'reset':
return 0
default:
throw new Error('Unexpected action')
}
}
</code></pre>
<p>We first define an initialState and a reducer. Note that the state here is a number, not an object. Redux users might get confused, but this is just fine. Furthermore, the action is a plain string here.
The following is a component with useReducer.</p>
<pre><code class="language-js">const Example01 = () => {
const [count, dispatch] = useReducer(reducer, initialState)
return (
<div>
{count}
<button onClick={() => dispatch('increment')}>+1</button>
<button onClick={() => dispatch('decrement')}>-1</button>
<button onClick={() => dispatch('reset')}>reset</button>
</div>
)
}
</code></pre>
<p>When a user clicks a button, it will dispatch an action which updates the count and the updated count will be displayed. You could define as many actions as possible in the reducer, but the limitation of this pattern is that actions are finite.
The full working code can be found below:</p>
<h3>App.js</h3>
<pre><code class="language-js"></code></pre>
<h3>Second way: Action object</h3>
<p>👉 This example is the one that is familiar to Redux users. We use <strong>a state object and an action object</strong>.</p>
<pre><code class="language-js">const initialState = {
count1: 0,
count2: 0,
}
const reducer = (state, action) => {
switch (action.type) {
case 'increment1':
return { ...state, count1: state.count1 + 1 }
case 'decrement1':
return { ...state, count1: state.count1 - 1 }
case 'set1':
return { ...state, count1: action.count }
case 'increment2':
return { ...state, count2: state.count2 + 1 }
case 'decrement2':
return { ...state, count2: state.count2 - 1 }
case 'set2':
return { ...state, count2: action.count }
default:
throw new Error('Unexpected action')
}
}
</code></pre>
<p>In this example, we keep two numbers in a state. We could use a complex object for a state as long as we organize a reducer well (ref: combineReducers). Because the action in this example is an object, we can put values like action.count in addition to a type. The reducer in this example is a bit of mess, but this allows us to simplify the component as the following.</p>
<pre><code class="language-js">const Example02 = () => {
const [state, dispatch] = useReducer(reducer, initialState)
return (
<>
<div>
{state.count1}
<button onClick={() => dispatch({ type: 'increment1' })}>+1</button>
<button onClick={() => dispatch({ type: 'decrement1' })}>-1</button>
<button onClick={() => dispatch({ type: 'set1', count: 0 })}>
reset
</button>
</div>
<div>
{state.count2}
<button onClick={() => dispatch({ type: 'increment2' })}>+1</button>
<button onClick={() => dispatch({ type: 'decrement2' })}>-1</button>
<button onClick={() => dispatch({ type: 'set2', count: 0 })}>
reset
</button>
</div>
</>
)
}
</code></pre>
<p>Notice there are two counters in a state, and action types are defined to update one counter out of the two.
See the full working code below:</p>
<pre><code class="language-js"></code></pre>
<h3>Third way: Multiple useReducers</h3>
<p>The previous example has two counters with a single state, which is a typical approach for global state. Because we are only working with local state, there is another way. We can use useReducer twice. Let’s look at the reducer.</p>
<pre><code class="language-js">const initialState = 0
const reducer = (state, action) => {
switch (action.type) {
case 'increment':
return state + 1
case 'decrement':
return state - 1
case 'set':
return action.count
default:
throw new Error('Unexpected action')
}
}
</code></pre>
<p>The state here is a simple number instead of an object, which is the same in Example01. Note that the action here is an object, which is different from that in Example01.
The component using this reducer will be the following.</p>
<pre><code class="language-js">const Example03 = () => {
const [count1, dispatch1] = useReducer(reducer, initialState)
const [count2, dispatch2] = useReducer(reducer, initialState)
return (
<>
<div>
{count1}
<button onClick={() => dispatch1({ type: 'increment' })}>+1</button>
<button onClick={() => dispatch1({ type: 'decrement' })}>-1</button>
<button onClick={() => dispatch1({ type: 'set', count: 0 })}>
reset
</button>
</div>
<div>
{count2}
<button onClick={() => dispatch2({ type: 'increment' })}>+1</button>
<button onClick={() => dispatch2({ type: 'decrement' })}>-1</button>
<button onClick={() => dispatch2({ type: 'set', count: 0 })}>
reset
</button>
</div>
</>
)
}
</code></pre>
<p>As you can see, we have two dispatch functions for each counter. We share the same reducer function for both.
The functionality is identical to that of Example02. The full working code is below.</p>
<h2>Fourth way: <strong>TextInput</strong></h2>
<p>Let’s look at a realistic example in which multiple useReducers work well. Suppose we have a React Native-like TextInput component, and we want to store text in local state. We can use a dispatch function to update the text.</p>
<pre><code class="language-js">const initialState = ''
const reducer = (state, action) => action
</code></pre>
<p>Note that the old state is just thrown away each time the reducer is called. The component using this is the following.</p>
<pre><code class="language-js">const Example04 = () => {
const [firstName, changeFirstName] = useReducer(reducer, initialState)
const [lastName, changeLastName] = useReducer(reducer, initialState)
return (
<>
<div>
First Name:
<TextInput value={firstName} onChangeText={changeFirstName} />
</div>
<div>
Last Name:
<TextInput value={lastName} onChangeText={changeLastName} />
</div>
</>
)
}
</code></pre>
<p>How simple it is. You could add some validation logic in reducer too. See the full example code below.</p>
<pre><code class="language-js"></code></pre>
<h2>Fifth way: Context</h2>
<p>At some point, we might want to share state between components a.k.a global state. In general, global state tends to limit component reusability, hence first consider using local state and only passing them (incl. dispatch) by props. When it doesn’t work well, Context is a rescue. If you are not familiar with Context API, check out the official document and how to use useContext.
In this example, we use the same reducer in Example03. The following is the code on how to create a context.</p>
<pre><code class="language-js">const CountContext = React.createContext()
const CountProvider = ({ children }) => {
const contextValue = useReducer(reducer, initialState)
return (
<CountContext.Provider value={contextValue}>
{children}
</CountContext.Provider>
)
}
const useCount = () => {
const contextValue = useContext(CountContext)
return contextValue
}
</code></pre>
<p>The function <code>useCount</code> is called <strong>custom hooks</strong> which can be used just like normal hooks. More about custom hooks,read the <a href="https://reactjs.org/docs/hooks-custom.html">official document</a>.
The component code is the following with <code>useCount</code>.</p>
<pre><code class="language-js">const Counter = () => {
const [count, dispatch] = useCount()
return (
<div>
{count}
<button onClick={() => dispatch({ type: 'increment' })}>+1</button>
<button onClick={() => dispatch({ type: 'decrement' })}>-1</button>
<button onClick={() => dispatch({ type: 'set', count: 0 })}>reset</button>
</div>
)
}
</code></pre>
<p>As our contextValue is just the result of useReducer, we destructure the result of useCount in the same way. Note that, at this point, it’s uncertain which context is used.
Finally, here’s the code to use it.</p>
<pre><code class="language-js">const Way5 = () => (
<>
<CountProvider>
<Counter />
<Counter />
</CountProvider>
<CountProvider>
<Counter />
<Counter />
</CountProvider>
</>
)
</code></pre>
<p>We have two CountProviders here. It means there are two counters, even though we have only one context. The Counters inside the same CountProvider shares the state. You might need to learn how this works by running the example code and trying it.
The full working code is below.</p>
<h2>Sixth Way: Subscription</h2>
<p>🛑 <strong>Context</strong> is the preferred way to share state among components, but what if we already have a shared state outside of React components. We can technically subscribe to such a shared state and update components when the shared state is updated. This pattern has limitations and React team provides a utility package: create-subscription.
Unfortunately, the utility package is not yet for React Hooks as of writing, so we do our best with hooks for now. Let’s try to reproduce the same functionality of Example05 without Context.
First, here’s a tiny custom hook to be used.</p>
<pre><code class="language-js">const useForceUpdate = () => useReducer((state) => !state, false)[1]
</code></pre>
<p>This reducer is simply to invert the previous state, ignoring the action. [1] is to return dispatch without destructuring. Next up is the main function to create a shared state and returns a custom hook.</p>
<pre><code class="language-js">const createSharedState = (reducer, initialState) => {
const subscribers = []
let state = initialState
const dispatch = (action) => {
state = reducer(state, action)
subscribers.forEach((callback) => callback())
}
const useSharedState = () => {
const forceUpdate = useForceUpdate()
useEffect(() => {
const callback = () => forceUpdate()
subscribers.push(callback)
callback() // in case it's already updated
const cleanup = () => {
const index = subscribers.indexOf(callback)
subscribers.splice(index, 1)
}
return cleanup
}, [])
return [state, dispatch]
}
return useSharedState
}
</code></pre>
<p>We use a new useEffect hook. It’s a very important hook, and you should carefully read the official document to learn how it works. In useEffect, we subscribe a callback to force update the component. We also clean up the subscription when the component is unmounted.
Let us create two shared states. We use the same reducer and initialState in Example05 and Example03.</p>
<pre><code class="language-js">const useCount1 = createSharedState(reducer, initialState)
const useCount2 = createSharedState(reducer, initialState)
</code></pre>
<p>Unlike useCount in Example05, these hooks are tied to specific shared states. We then use these two hooks.</p>
<pre><code class="language-js">const Counter = ({ count, dispatch }) => (
<div>
{count}
<button onClick={() => dispatch({ type: 'increment' })}>+1</button>
<button onClick={() => dispatch({ type: 'decrement' })}>-1</button>
<button onClick={() => dispatch({ type: 'set', count: 0 })}>reset</button>
</div>
)
const Counter1 = () => {
const [count, dispatch] = useCount1()
return <Counter count={count} dispatch={dispatch} />
}
const Counter2 = () => {
const [count, dispatch] = useCount2()
return <Counter count={count} dispatch={dispatch} />
}
</code></pre>
<p>🛑 the Counter component is a stateless component in common. Finally, we use these components.</p>
<pre><code class="language-js">const Example06 = () => (
<>
<Counter1 />
<Counter1 />
<Counter2 />
<Counter2 />
</>
)
</code></pre>]]></content:encoded>
</item>
<item>
<title><![CDATA[Conditional Rendering]]></title>
<link>http://irenaapp.de//blog-react-post-conditional-rendering/</link>
<guid>http://irenaapp.de//blog-react-post-conditional-rendering/</guid>
<pubDate>Thu, 12 Nov 2020 23:14:21 GMT</pubDate>
<description><![CDATA[Conditional Rendering 🤔 Conditional rendering in React isn't difficult. In JSX - the syntax extension used for React - you can use plain…]]></description>
<content:encoded><![CDATA[<h3>Conditional Rendering 🤔</h3>
<p>Conditional rendering in React isn't difficult. In JSX - the syntax extension used for React - you can use plain JavaScript which includes if else statements, ternary operators, switch case statements, and much more. In a conditional render, a React component decides based on one or several conditions which DOM elements it will return</p>
<p>When a component has a conditional rendering, the appearance of the rendered component differs based on the condition.</p>
<p>👉 Conditional Rendering in React: <code>if</code></p>
<p>Conditional Rendering in React: if else</p>
<p>Conditional Rendering in React: ternary</p>
<p>Conditional Rendering in React: &&</p>
<p>Conditional Rendering in React: switch case</p>
<p>Multiple Conditional Renderings in React</p>
<p>Nested Conditional Rendering in React</p>
<p>Conditional Rendering with HOC
If Else Components in React</p>
<h2>CONDITIONAL RENDERING IN REACT: IF</h2>
<p>The most basic conditional rendering logic in React is done with a single if statement. Imagine you don't want to render something in your React component, because it doesn't have the necessary React props available. For instance, a List component in React shouldn't render the list HTML elements in a view if there is no list of items in the first place. You can use a plain JavaScript if statement to return earlier (guard pattern):</p>
<pre><code class="language-js">const users = [
{ id: '1', firstName: 'Daniel', lastName: 'Smith' },
{ id: '2', firstName: 'Tom', lastName: 'Garlov' },
]
function App() {
return (
<div>
<h1>Conditional Rendering</h1>
<List list={users} />
</div>
)
}
function List({ list }) {
if (!list) {
return null
}
return (
<ul>
{list.map((item) => (
<Item key={item.id} item={item} />
))}
</ul>
)
}
function Item({ item }) {
return (
<li>
{item.firstName} {item.lastName}
</li>
)
}
</code></pre>
<p>👉 In this code, the conditional rendering is based on props, but the conditional rendering could be based on state and hooks too.</p>
<h2>CONDITIONAL RENDERING IN REACT: IF ELSE</h2>
<p>Let's move on with the previous example to learn about if else statements in React. If there is no list, we render nothing and hide the HTML as we have seen before with the single if statement. However, you may want to show a text as feedback for your user when the list is empty for a better user experience. This would work with another single if statement, but we will expand the example with an if else statement instead:</p>
<pre><code class="language-js">function List({ list }) {
if (!list) {
return null
}
if (!list.length) {
return <p>Sorry, the list is empty.</p>
} else {
return (
<div>
{list.map((item) => (
<Item item={item} />
))}
</div>
)
}
}
</code></pre>]]></content:encoded>
</item>
<item>
<title><![CDATA[How to Life Cycling 🚲 in React? 🤔]]></title>
<link>http://irenaapp.de//blog-react-post-lifecycle/</link>
<guid>http://irenaapp.de//blog-react-post-lifecycle/</guid>
<pubDate>Tue, 10 Nov 2020 23:14:21 GMT</pubDate>
<description><![CDATA[Life Cycle Methods in React When developing in React, every Component follows a cycle from when it’s created and mounted on the DOM to when…]]></description>
<content:encoded><![CDATA[<h3>Life Cycle Methods in React</h3>
<p>When developing in React, every Component follows a cycle from when it’s created and mounted on the DOM to when it is <strong>unmounted</strong> and <strong>destroyed</strong>. This is what we refer to as the <strong>Component lifecycle</strong>. React provides <strong>hooks</strong>, methods that get called automatically at each point in the lifecycle, that give you good control of what happens at the point it is invoked. A good understanding of these hooks will give you the power to effectively control and manipulate what goes on in a component throughout its lifetime.</p>
<p>This lifecycle of events that the React component goes through is broadly categorized into three parts: <strong>Mounting, Updating and Unmounting</strong>. However, React 16 introduced a new method which, in this tutorial, we will allow to stand on its own. We will discuss each of these methods and how they can be used.</p>
<h2><strong>Mounting methods</strong></h2>
<p>🛑 <strong>A component mounts when it is created and first inserted into the DOM - when it is rendered for the first time.</strong> The methods that are available during this period are:</p>
<p>👉 <strong>constructor()</strong></p>
<p>👉 <strong>componentWillMount()</strong></p>
<p>👉 <strong>render()</strong></p>
<p>👉 <strong>componentDidMount()</strong></p>
<p>⚠️ 👉 The constructor and render methods are part of the basic concepts of React which this article assumes you are familiar with. We’ll proceed to discuss the other mounting methods.</p>
<h3><strong>The componentWillMount() Hook</strong></h3>
<p>⚠️ componentWillMount will be deprecated in React 16.3. You can use the <strong>constructor method</strong> or <code>componentDidMount</code> depending on what you need to be done. constructor will be called <strong>pre-render and componentDidMount post-render</strong>.</p>
<p>👉 The <code>componentWillMount</code> method is called right before a component mounts or the render method is called. The truth is that you might hardly make use of this method in your React application. Let me explain why.</p>
<p>The <strong>componentWillMount</strong> method sits between the constructor method and the render method which puts it in a very odd position. Since it’s before the render method, it can be used to set the default configuration for a component, but this is mostly done using the constructor method. And since nothing changes between these two methods, there will be no need to set the configuration again.</p>
<p>Also, the <strong>render</strong> method has not been called at this point so nothing can be done with the DOM of the component since it has not been mounted. Some might think that this is the right place to make API calls for client-side rendering but this should not be done. API calls are asynchronous and the data might not be returned before the render method gets called. This means that the component might render with empty data at least once.</p>
<p>However, one good way to make use of this method is to perform any setup that can be done at runtime, for instance connecting to external APIs like Firebase. This setup should typically be done at the highest level of your component, like your root component, so the majority of your components will likely not make use of this method.</p>
<p>Here’s a simple example that you can try to see that this method actually gets called before the component is rendered:</p>
<pre><code class="language-js">class Study extends React.Component {
componentWillMount() {
console.log('I am about to say hello')
}
render() {
return <h1>Hello </h1>
}
}
</code></pre>
<h3><strong>The componentDidMount() method</strong></h3>
<p>This method is available after the component has mounted. That is after the HTML from render has finished loading. It is called once in the component life cycle and it signals that the component and all its sub-components have rendered properly.</p>
<p>This is the best place to make API calls since, at this point, the component has been mounted and is available to the DOM. Generally, componentDidMount is a good place to do all the setup you couldn’t have done without the DOM. So here is a bunch of things you can do with this method:</p>
<p>👉 Connect a React app to external applications, such as web APIs or JavaScript frameworks.</p>
<p>👉 Set Timers using using setTimeout or setInterval.</p>
<p>👉 Add event listeners.</p>
<p>👉 Draw on an element you just rendered.</p>
<p>Practically, anything that should be setup in the DOM can be done here. So here’s an example of using the componentDidMount method to make API calls:</p>
<pre><code class="language-js">class Study extends React.Component {
componentDidMount() {
fetch(url).then((results) => {
// Do something with the results
})
}
}
</code></pre>
<h2>Updating methods</h2>
<p>Components do not always remain in the same state after mounting. Sometimes the underlying props could change and the component has to be re-rendered. The updating lifecycle methods give you control over when and how this updating should take place.</p>
<p>There are five updating lifecycle methods and they are called in the order they appear below:</p>
<h3><strong>componentWillReceiveProps()</strong></h3>
<h3><strong>shouldComponentUpdate()</strong></h3>
<h3><strong>componentWillUpdate()</strong></h3>
<h3><strong>render()</strong></h3>
<h3><strong>componentDidUpdate()</strong></h3>
<p>We won’t discuss the render method as the article assumes you have knowledge of React already. Let’s discuss the others.</p>
<h2>The componentWillReceiveProps() method</h2>
<p><strong>Props</strong> are externally passed into a component by its parent component. Sometimes these props are hooked to the state of the parent component. So if the state of the parent component changes, the props passed to the component changes and it has to be updated. If the props are tied to the state of the component, a change in it will mean a change in the state of the component.</p>
<p>👉 <strong>componentWillReceiveProps()</strong> is a method that is called before a component does anything with the new props. This method is called with the new props passed as an argument. Here, we have access to the next set of props and the present ones. Therefore, using this method, we can compare the present props with the new ones and check if anything has really changed.</p>
<p>🛑 React may call this method even though nothing has really changed so make sure to make a comparison. If nothing has changed, there will be no need to change the state of the component. But if it has changed, then this change can be acted upon.</p>
<p>Here’s an example of the method in use:</p>
<pre><code class="language-js">class Study extends React.Component {
constructor(props) {
super(props)
this.state = { number: this.props.number }
}
componentWillReceiveProps(nextProps) {
if (this.props.number !== nextProps.number) {
this.setState({ number: nextProps.number })
}
}
render() {
return <h1>{this.state.number}</h1>
}
}
</code></pre>
<p>In the example above, this.state.number will only be updated if the new number is different from the previous one. So if there’s no difference then the state is not updated.</p>
<h2><strong>The shouldComponentUpdate() method</strong></h2>
<p>This method is called before the component re-renders after receiving a new set of props or there’s a new state. We can see that it receives two arguments, the next props, and the next state. The default behavior is for a component to re-render once there’s a change of state of props.</p>
<p>shouldComponentUpdate is used to let React know that a component’s output is not affected by a change of props or state in the component and thus should not re-render. It returns either a true or false value. If it returns true, the component will go ahead and do what it always does, re-render the component. If it returns false then the component will not update. Note that this does not prevent child components from re-rendering when their state changes.</p>
<p>The best way to use this method is to have it return false and hence the component will not update under certain conditions. If those conditions are met, then the component does not update.</p>
<p>In the example below, the component will only update if the new input is different from the previous:</p>
<pre><code class="language-js">class Study extends React.Component {
[...]
shouldComponentUpdate(nextProps, nextState) {
if (this.state.input == nextState.input) {
return false;
}
}
[...]
}
</code></pre>
<p><strong>shouldComponentUpdate</strong> is a great place to improve the performance of a component because it can help to prevent unnecessary re-rendering. However, it is advised not to use this method for deep equality checks or JSON.stringify as this is very inefficient and may harm performance.</p>
<h2><strong>The componentWillUpdate() method</strong></h2>
<p><strong>componentWillUpdate</strong> is the method that can be used to perform preparation before re-rendering occurs. You cannot call this.setState in this method.</p>
<p>One major thing that can be done with this method is to interact with things outside of the React architecture. Also, if you need to do any non-React setup before a component renders such as interacting with an API or checking the window size, componentWillUpdate can be used.</p>
<p>Another time to use this method is if you are using shouldComponentUpdate and need to do something when the props change. In this scenario, it is preferable to use it instead of componentWillReceiveProps and it will be called only when the component will actually be re-rendered. However, if you need state to change in response to change in props, use componentWillReceiveProps instead.</p>
<p>While it can be used to perform animations and other effects, it should not be done as this method might be called multiple times before the component is actually re-rendered.</p>
<pre><code class="language-js">
class Study extends React.Component {
[...]
componentWillUpdate(nextProps, nextState) {
// Do something here
}
[...]
}
</code></pre>
<h2><strong>The componentDidUpdate() method</strong></h2>
<p>componentDidUpdate is called after any rendered HTML has finished loading. It receives two arguments, the props and state of the component before the current updating period began.</p>
<p>componentDidUpdate is the best place to perform an interaction with a non-React environment like the browser or making HTTP requests. This should be done as long as you compare the current props to the previous props to avoid unnecessary network requests.</p>
<p>Here is an example of it in use:</p>
<pre><code class="language-js">
class Study extends React.Component {
[...]
componentDidUpdate(prevProps, prevState) {
if (this.props.input == prevProps.input) {
// make ajax calls
// Perform any other function
}
}
[...]
}
</code></pre>
<h2><strong>Unmounting methods</strong></h2>
<p>Components do not always stay in the DOM. Sometimes they have to be removed due to changes in state or something else. The unmounting method will help us handle the unmounting of components. We say method because there is just one method as at React 16.</p>
<p>The componentWillUnmount() method
This is the only unmounting method. componentWillUnmount is called right before a component is removed from the DOM. This is where you can perform any cleanups that should be done such as invalidating timers, canceling network requests, removing event listeners or canceling any subscriptions made in componentDidMount.</p>
<pre><code class="language-js">class Study extends React.Component {
[...]
componentWillUnmount() {
document.removeEventListener("click", SomeFunction);
}
[...]
}
</code></pre>
<h2><strong>The componentDidCatch() method</strong></h2>
<p>👉 This lifecycle method was added in React 16 and is used in error boundaries.</p>
<p>A component becomes an error boundary if it defines the componentDidCatch method. In this method, this.setState can be called and used to catch an unhandled JavaScript error in a child component tree and display a fallback UI instead of the component that crashed. These errors are caught during rendering, in lifecycle methods, and in constructors of the whole tree below them.
This is to ensure that an error in a child component does not break the whole app.</p>
<p>It is important to note that this method only catches errors in child components and not in the component itself.</p>
<p>This method has two parameters. The first is the actual error thrown. The second parameter is an object with a componentStack property containing the component stack trace information. With these parameters, you can set the error info in state and return an appropriate message in its render method or log to a reporting system.</p>
<p>Here’s an example of how this method can be used in error boundaries:</p>
<pre><code class="language-js">class ErrorBoundary extends React.Component {
constructor(props) {
super(props)
this.state = { hasError: false }
}
componentDidCatch(error, info) {
this.setState({ hasError: true })
}
render() {
if (this.state.hasError) {
return <h1> Oops!!! Broken </h1>
}
return this.props.children
}
}
</code></pre>
<h2>React lifecycle Overview 🤓</h2>
<table>
<thead>
<tr>
<th align="left">Method</th>
<th align="center">Side effects<sup>1</sup></th>
<th align="center">State updates<sup>2</sup></th>
<th align="left">Example uses</th>
</tr>
</thead>
<tbody>
<tr>
<td align="left"><big><strong>Mounting</strong></big></td>
<td align="center"></td>
<td align="center"></td>
<td align="left"></td>
</tr>
<tr>
<td align="left"><code>componentWillMount</code></td>
<td align="center"></td>
<td align="center">✓</td>
<td align="left">Constructor equivalent for <code>createClass</code></td>
</tr>
<tr>
<td align="left"><code>render</code></td>
<td align="center"></td>
<td align="center"></td>
<td align="left">Create and return element(s)</td>
</tr>
<tr>
<td align="left"><code>componentDidMount</code></td>
<td align="center">✓</td>
<td align="center">✓</td>
<td align="left">DOM manipulations, network requests, etc.</td>
</tr>
<tr>
<td align="left"><big><strong>Updating</strong></big></td>
<td align="center"></td>
<td align="center"></td>
<td align="left"></td>
</tr>
<tr>
<td align="left"><code>componentWillReceiveProps</code></td>
<td align="center"></td>
<td align="center">✓</td>
<td align="left">Update <code>state</code> based on changed <code>props</code></td>
</tr>
<tr>
<td align="left"><code>shouldComponentUpdate</code></td>
<td align="center"></td>
<td align="center"></td>
<td align="left">Compare inputs and determine if render needed</td>
</tr>
<tr>
<td align="left"><code>componentWillUpdate</code></td>
<td align="center"></td>
<td align="center"></td>
<td align="left">Set/reset things (eg cached values) before next render</td>
</tr>
<tr>
<td align="left"><code>render</code></td>
<td align="center"></td>
<td align="center"></td>
<td align="left">Create and return element(s)</td>
</tr>
<tr>
<td align="left"><code>componentDidUpdate</code></td>
<td align="center">✓</td>
<td align="center">✓</td>
<td align="left">DOM manipulations, network requests, etc.</td>
</tr>
<tr>
<td align="left"><big><strong>Unmounting</strong></big></td>
<td align="center"></td>
<td align="center"></td>
<td align="left"></td>
</tr>
<tr>
<td align="left"><code>componentWillUnmount</code></td>
<td align="center">✓</td>
<td align="center"></td>
<td align="left">DOM manipulations, network requests, etc.</td>
</tr>
</tbody>
</table>
<h3>Reference</h3>
<p><a href="https://devhints.io/react">React Lifecycle</a></p>
<p>🤓 <strong>Happy Coding!</strong> 🌴 🐘 🤖</p>]]></content:encoded>
</item>
<item>
<title><![CDATA[Array methods in React]]></title>
<link>http://irenaapp.de//blog-react-post-array-methods/</link>
<guid>http://irenaapp.de//blog-react-post-array-methods/</guid>
<pubDate>Tue, 10 Nov 2020 23:14:21 GMT</pubDate>
<description><![CDATA[Array Methods in React 🤔 Let’s consider what is an array method. Simply put, an array method is a method that can be called on an array to…]]></description>
<content:encoded><![CDATA[<h3>Array Methods in React 🤔</h3>
<p>Let’s consider what is an array method. Simply put, an array method is a method that can be called on an array to perform an action on or with that array. Here are a few javascript array methods used in react.</p>
<p><strong>.map()</strong></p>
<p>This array method takes in a function that will be called on each element in a given array and it returns a new set of an array without modifying the original array. Simply put, it helps us create a new set of array based on an existing one.</p>
<p>The code below shows a new set of an array after using the map method to add 3 to each element in the numbers array.</p>
<pre><code class="language-js">const numbers = [1, 3, 5, 7]
const newNumbers = numbers.map((number) => number + 3)
// newNumbers will be equal to ['4', '6', '8', '10']
</code></pre>
<p><strong>.reduce()</strong></p>
<p>This is a great array method that uses an accumulator to reduce all elements in an array to a single value. It basically takes in two augments, a callback function and an initial value, performs an action, and returns a single value, the value being any type i.e. object, array, string, integer.
👉 <strong>The call back function takes in two parameters namely: accumulator and current value.</strong></p>
<p>The code snippet below shows a single or the cumulated value being returned, after using the reduce method to add the accumulated value with the current value, the function is iterating over.</p>
<pre><code class="language-js">const numbers = [1, 2, 3, 4, 5]
const newValue = numbers.reduce(
(accumulator, currentValue) => accumulator + currentValue
)
console.log(newValue)
// newValue will return 15
</code></pre>
<p>It is also worthy of mentioning that there are other cool features you can use the array method to do. For more on that, check the MDN docs for example of that. Be sure to thank me later😁</p>
<p><strong>.filter()</strong></p>
<p>Just as it sounds, it works similar to the way the .map() method works. It filters an array based on if an element in the array, meets the condition passed in the function and then, it returns an array.</p>
<pre><code class="language-js">const numbers = [1, 2, 3, 4, 5, 6, 7]
const newValue = numbers.filter((number) => number >= 3)
console.log(newValue)
// newValue will return [3, 4, 5, 6, 7]
</code></pre>
<p><strong>.includes()</strong></p>
<p>This method simply checks if an element exists in a given array and returns a boolean(true or false). Do note that there are some constraints with regards to the data types that the include method can check for. This is because of the way Javascript treats objects and primitive types.</p>
<pre><code class="language-js">const numbers = [1, 2, 3, 4, 5]
const newValue = numbers.includes(3)
console.log(newValue)
// newValue will return true
</code></pre>
<p><strong>.find()</strong></p>
<p>This method takes in a function that checks for a specific element in an array and returns the very first occurrence of the condition.</p>
<pre><code class="language-js">const numbers = [1, 2, 3, 4]
const newValue = numbers.find((number) => number > 3)
console.log(newValue)
// newValue will return 4
</code></pre>
<h3><strong>.forEach()</strong></h3>
<p>Applies a function on each item in an array.</p>
<p>Log each array item to the console</p>
<pre><code class="language-js">const emotions = ['happy', 'sad', 'angry']
emotions.forEach((emotion) => console.log(emotion))
// Will log the following:
// 'happy'
// 'sad'
// 'angry'
</code></pre>
<p>👉 counting duplicate values</p>
<pre><code class="language-js">uniqueCount = [
'1',
'2',
'3',
'4',
'4',
'5',
'1',
'2',
'3',
'6',
'8',
'9',
'9',
'9',
'5',
'8',
]
let count = {}
uniqueCount.forEach(function (i) {
count[i] = (count[i] || 0) + 1
})
console.log(count)
</code></pre>
<h3><strong>.some()</strong></h3>
<p>Checks if any item in an array passes the condition. A good use case would be checking for user privileges. It can also be used similarly to a .forEach() where you would perform an action on each array item and break out of the loop once a truthy value is returned.</p>
<p>👉 Check if there is at least one 'admin' in an array.</p>
<pre><code class="language-js">const userPrivileges = ['user', 'user', 'user', 'admin']
const containsAdmin = userPrivileges.some((element) => element === 'admin')
// containsAdmin will be equal to true
</code></pre>
<h3><strong>.every()</strong></h3>
<p>Similar to .some(), but checks if all items in an array pass a condition.
Example
Check if all ratings are equal to or greater than 3 stars.</p>
<pre><code class="language-js">const ratings = [3, 5, 4, 3, 5]
const goodOverallRating = ratings.every((rating) => rating >= 3)
// goodOverallRating will be equal to true
</code></pre>
<h3><strong>Array.from()</strong></h3>
<p>This is a static method that creates an array based on another array or string. You can also pass a map callback function as an argument to further shape the data in the new array. I’m not too sure why someone would use this over the <strong>.map()</strong> method.</p>
<p>Create an array from a string.</p>
<pre><code class="language-js">const newArray = Array.from('hello')
// newArray will be equal to ['h', 'e', 'l', 'l', 'o']
</code></pre>
<p>Create an array that has double the value for each item in another array.</p>
<pre><code class="language-js">const doubledValues = Array.from([2, 4, 6], (number) => number * 2)
// doubleValues will be equal to [4, 8, 12]
</code></pre>
<h3><strong>Object.values()</strong></h3>
<p>Return an array of the values of an object.</p>
<pre><code class="language-js">const icecreamColors = {
chocolate: 'brown',
vanilla: 'white',
strawberry: 'red',
}
const colors = Object.values(icecreamColors)
// colors will be equal to ["brown", "white", "red"]
</code></pre>
<h3><strong>Object.keys()</strong></h3>
<p>Return an array of the keys of an object.</p>
<pre><code class="language-js">const icecreamColors = {
chocolate: 'brown',
vanilla: 'white',
strawberry: 'red',
}
const types = Object.keys(icecreamColors)
// types will be equal to ["chocolate", "vanilla", "strawberry"]
</code></pre>
<h3><strong>Object.entries()</strong></h3>
<p>Creates an array which contains arrays of key/value pairs of an object.</p>
<pre><code class="language-js">const weather = {
rain: 0,
temperature: 24,
humidity: 33,
}
const entries = Object.entries(weather)
// entries will be equal to
// [['rain', 0], ['temperature', 24], ['humidity', 33]]
</code></pre>
<h3>🛑 <strong>Array spread</strong></h3>
<p>👉 Spreading arrays using the spread operator <strong>(…)</strong> allows you to <strong>expand the elements in an array.It’s useful when concatenating a bunch of arrays together.</strong> It’s also a good way to avoid using the <strong>splice() method</strong> when looking to remove certain elements from an array because it can be combined with the <strong>slice()</strong> method to prevent direct mutation of an array.</p>
<pre><code class="language-js">Combine two arrays.
const spreadableOne = [1, 2, 3, 4];
const spreadableTwo = [5, 6, 7, 8];
const combined = [...spreadableOne, ...spreadableTwo];
// combined will be equal to [1, 2, 3, 4, 5, 6, 7, 8]
</code></pre>
<p>Remove an array element without mutating the original array.</p>
<pre><code class="language-js">const animals = ['squirrel', 'tiger', 'lion', 'horse', 'rabbit']
const mammals = [...animals.slice(0, 3), ...animals.slice(4)]
// mammals will be equal to ['squirrel', 'tiger', 'lion', 'rabbit']
</code></pre>
<h3><strong>Object spread</strong></h3>
<p>Spreading an object allows for the addition of new properties and values to an object without mutations (i.e. a new object is created) and it can also be used to combine multiple objects together. It should be noted that <strong>spreading objects does not do nested copying.</strong></p>
<p>👉 Add a new object property and value without mutating the original object.</p>
<pre><code class="language-js">const spreadableObject = {
name: 'Irene',
phone: 'iPhone',
}
const newObject = {
...spreadableObject,
carModel: 'Suzuki',
}
// newObject will be equal to
// { carModel: 'Suzuki', name: 'Irene', phone: 'iPhone' }
</code></pre>
<h3><strong>Function Rest</strong></h3>
<p>👉 Functions can use the rest parameter syntax to accept any number of arguments as an array.</p>
<pre><code class="language-js">Display the array of passed arguments.
function displayArgumentsArray(...theArguments) {
console.log(theArguments);
}
displayArgumentsArray('hi', 'there', 'bud');
// Will print ['hi', 'there', 'bud']
</code></pre>
<h3><strong>Object.freeze()</strong></h3>
<p>Prevents you from <strong>modifying existing object properties or adding new properties and values to an object.</strong> Actually <strong>const</strong> allows to modify an object.</p>
<p>Freeze an object to prevent the name property from being changed.</p>
<pre><code class="language-js">const frozenObject = {
name: 'Irene',
}
Object.freeze(frozenObject)
frozenObject.name = 'Mary'
// frozenObject will be equal to { name: 'Irene' }
</code></pre>
<h3><strong>Object.seal()</strong></h3>
<p>Stops any new properties from being added to an object, but still allows for existing properties to be changed.</p>
<p>👉 Seal an object to prevent the wearsWatch property from being added.</p>
<pre><code class="language-js">const sealedObject = {
name: 'Irene',
}
Object.seal(sealedObject)
sealedObject.name = 'Mary'
sealedObject.wearsWatch = true
// sealedObject will be equal to { name: 'Mary' }
</code></pre>
<h3><strong>Object.assign()</strong></h3>
<p>Allows for objects to be combined together. This method is not really needed because you can use the object spread syntax instead. Like the object spread operator, Object.assign() does not do deep cloning. Lodash is your best friend when it comes to deep cloning objects.</p>
<p>👉 Combine two objects into one.</p>
<pre><code class="language-js">const firstObject = {
firstName: 'Irene',
}
const secondObject = {
lastName: 'Simpson',
}
const combinedObject = Object.assign(firstObject, secondObject)
// combinedObject will be equal to { firstName: 'Irene', lastName: 'Simpson' }
</code></pre>
<h3><strong>Math.floor() / Math.random()</strong></h3>
<p>chose random number from array react</p>
<pre><code class="language-js">let items = ['Yes', 'No', 'Maybe']
let item = items[Math.floor(Math.random() * items.length)]
</code></pre>
<p>👉 Pick a random element</p>
<pre><code class="language-js">let myArray = ['Apples', 'Bananas', 'Pears']
let randomItem = myArray[Math.floor(Math.random() * myArray.length)]
</code></pre>
<p>👉 get a random string from a array</p>
<ul>
<li>a random string</li>
</ul>
<pre><code class="language-js">const randomElement = array[Math.floor(Math.random() * array.length)]
</code></pre>
<pre><code class="language-js">let groceries = ['milk', 'coriander', 'cucumber', 'eggplant']
let mygroceries = groceries[Math.floor(Math.random() * groceries.length)]
console.log(mygroceries) //This gives you any string from groceries
</code></pre>
<pre><code class="language-js">array.sort(() => Math.random() - Math.random()).slice(0, n)
</code></pre>
<pre><code class="language-js">let items = ['Yes', 'No', 'Maybe']
let item = items[Math.floor(Math.random() * items.length)]
</code></pre>
<p><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array">Read more about JavaScript Array class</a></p>
<p>🐘 🌴</p>]]></content:encoded>
</item>
<item>
<title><![CDATA[JavaScript Variables, Scope and Hoisting]]></title>
<link>http://irenaapp.de//blog-javascript-variables-post/</link>
<guid>http://irenaapp.de//blog-javascript-variables-post/</guid>
<pubDate>Tue, 10 Nov 2020 23:10:51 GMT</pubDate>
<description><![CDATA[Variables, Scope and Hoisting in JavaScript Introduction We must understand how variable scope and variable hoisting work in JavaScript, if…]]></description>
<content:encoded><![CDATA[<p>Variables, Scope and Hoisting in JavaScript</p>
<h3>Introduction</h3>
<p>We must understand how variable scope and variable hoisting work in JavaScript, if want to understand JavaScript well.</p>
<p>Variables are one of the fundamental blocks of any programming language, the way each language defines how we declare and interact with variables can make or break a programming language. Thus any developer needs to understand how to effectively work with variables, their rules, and particularities.</p>
<p>So this makes <strong>Variables</strong> a fundamental programming concept, and one of the first and most important things to learn. In JavaScript, there are three ways to declare a variable - with the keywords var, let, and const.
Each with its own properties and particularities.</p>
<table>
<thead>
<tr>
<th>Keyword</th>
<th align="center">Scope</th>
<th align="right">Hoisting</th>
<th align="right">Can be reassigned</th>
</tr>
</thead>
<tbody>
<tr>
<td><strong>var</strong></td>
<td align="center">Function</td>
<td align="right">Yes</td>
<td align="right">yes</td>
</tr>
<tr>
<td><strong>let</strong></td>
<td align="center">Block</td>
<td align="right">No</td>
<td align="right">Yes</td>
</tr>
<tr>
<td><strong>const</strong></td>
<td align="center">Block</td>
<td align="right">No</td>
<td align="right">No</td>
</tr>
</tbody>
</table>
<p>In this article, we will learn what variables are, how to declare and name them, the difference between var, let, and const, and the significance of global and local scope.</p>
<h2>What are Variables?</h2>
<p>A variable is a named container used for storing values. A piece of information that we might reference multiple times can be stored in a variable for later use or modification.</p>
<p>Variables in algebra, frequently represented by x, are used to hold the value of an unknown number. In JavaScript, the value contained inside a variable can be more than just a number; it can be any JavaScript data type, such as a string or an object.</p>
<pre><code class="language-js">// Assign the string value Friendly to the username identifier
var username = 'friendly_dolphin'
</code></pre>
<p><strong>This statement consists of a few parts:</strong></p>
<p>The declaration of a variable using the var keyword
The variable name (or identifier), username
The assignment operation, represented by the = syntax
The value being assigned, "friendly_dolphin"
Now we can use username in code, and JavaScript will remember that username represents the string value friendly_dolphin.</p>
<pre><code class="language-js">// Check if variable is equal to value
if (username === 'friendly_dolphin') {
console.log(true)
}
</code></pre>
<h2>Variable Scope</h2>
<p><strong>Scope</strong> in JavaScript refers to context (or portion) of the code which determines the accessibility (visibility) of variables. In JavaScript, we have 2 types of scope, <strong>local and global</strong>. Though local scope can have different meanings.</p>
<p>Let’s work out through the definitions by giving some examples of how scoping works. Let’s say you define a variable message:</p>
<pre><code class="language-js">const message = 'Hello World'
console.log(message) // 'Hello World'
</code></pre>
<p>As you may expect the variable message used in the <strong>console.log</strong> would exist and have the value <code>Hello World</code>. No Doubts there, but what happens if I change a bit where I declare the variable:</p>
<pre><code class="language-js">if (true) {
const message = 'Hello World'
}
console.log(message) // ReferenceError: message is not defined
</code></pre>
<p>Looks like broken, but why? Actually <strong>if statement</strong> creates a local block scope, and since I used <strong>const</strong> the variable is only declared for that block scope, and cannot be accessed from the outside.</p>
<p>Let’s dig a bit more about block and function scopes.</p>
<h2>Block Scope</h2>
<p>A block is basically a section of code (zero or more statements) which is delimited by a pair of curly braces and may optionally be labeled.</p>
<p>As we already discussed the use of let and const allows us to define variables that live within the block scope. Next, we’ll build very similar examples by using different keywords to generate new scopes:</p>
<pre><code class="language-js">const x1 = 1
{
const x1 = 2
console.log(x1) // 2
}
console.log(x1) // 1
</code></pre>
<p>Let’s explain this one as it may look a bit strange at first. In our outer scope, I am defining the variable <code>x1</code> with a value of <code>1</code>. Then create a new block scope by simply using curly braces, this is strange, but totally legal within JavaScript, and in this new scope, I create a new variable (separate from the one in the outer scope) also named <code>x1</code>. But don’t get confused, this is a brand new variable, which will only be available within that scope.</p>
<p>Same example now with a named scope:</p>
<pre><code class="language-JS">const x2 = 1
myNewScope: { // Named scope
const x2 = 2
console.log(x2) // 2
}
console.log(x2) // 1
</code></pre>
<p>While example (DO NOT run the code below? 🍄 🤔)</p>
<pre><code class="language-js">const x3 = 1
while (x3 === 1) {
const x3 = 2
console.log(x3) // 2
}
console.log(x3) // Never executed
</code></pre>
<p>What’s wrong with that code? And what would happen if it is run?
👉 Let me explain, <code>x3</code> as declared in the outer scope is used for the while comparison <code>x3 === 1</code>, normally inside the while statement, I’d be able to reassign <code>x3</code> a <strong>new value and exit the loop</strong>, however as I am declaring a new <code>x3</code> withing the block scope, I cannot change <code>x3</code> from the outer scope anymore, and thus the while condition will always evaluate to true producing an infinite loop that will hang THE browser, or if you are using a terminal to run it on NodeJS will print a lot of <code>2</code>.</p>
<p>Fixing this particular code could be tricky unless you actually rename either variables.</p>
<p>So far in THE example, IS used <strong>const</strong>, but exactly the same behavior would happen with <strong>let</strong>. However, as we can see in the comparison table above that the keyword <strong>var</strong> is actually <strong>function scope</strong>, so what does it mean for the examples? Well… let’s take a look:</p>
<pre><code class="language-js">var x4 = 1
{
var x4 = 2
console.log(x4) // 2
}
console.log(x4) // 2
</code></pre>
<p>🤔 even though re-declared <code>x4</code>inside the scope it changed the value to <code>2</code> on the inner scope as well as the outer scope. An this is one of the most important differences between <strong>let, const, and var</strong> .</p>
<h3>Function Scope</h3>
<p>A function scope is in a way also a block scope, so let and const would behave the same way they did in our previous examples. However, function scopes also encapsulate variables declared with var. but let’s see that continuing with our xn examples:</p>
<p>🤔 <strong>const</strong> or <strong>let</strong> example:</p>
<pre><code class="language-js">const x5 = 1
function myFunction() {
const x5 = 2
console.log(x5) // 2
}
myFunction()
console.log(x5) // 1
</code></pre>
<p>👉as expected, now with <strong>var</strong></p>
<pre><code class="language-js">var x6 = 1
function myFunction() {
var x6 = 2
console.log(x6) // 2
}
myFunction()
console.log(x6) // 1
</code></pre>
<p>👉In this scenario, <strong>var</strong> worked the same way as <strong>let and const</strong>. Moreover:</p>
<pre><code class="language-js">function myFunction() {
var x7 = 1
}
console.log(x7) // ReferenceError: x7 is not defined
</code></pre>
<p>❗ ⚠️ Clearly, <strong>var</strong> declarations only exist within the function they were created in and can’t be accessed from the outside.</p>
<p>But there’s more to it, as always JS has been evolving, and newer type of scopes has been created.</p>
<h3>Module Scope</h3>
<p>With the introduction of modules in ES6, it was important for variables in a module not to directly affect variables in other modules. Can you imagine a world where importing modules from a library would conflict with your variables? Not even JS is that messy! So by definition modules create their own scope which encapsulates all variables created with var, let or const, similar to the function scope.</p>
<p>There are ways though that modules provide to export variables so they can be accessed from outside the module.</p>
<p>So far we talked about different types of local scopes, let’s now dive into global scopes.</p>
<h3>Global Scope</h3>
<p>A variable defined outside any function, block, or module scope has global scope. Variables in global scope can be accessed from everywhere in the application.</p>
<p>The global scope can sometimes be confused with module scope, but this is not the case, a global scope variable can be used across modules, though this is considered a bad practice, and for good reasons.</p>
<p>How would you go about declaring a global variable? It depends on the context, it is different on a browser than a NodeJS application. In the context of the browser, you can do something as simply as:</p>
<pre><code class="language-js"><script>let MESSAGE = 'Hello World' console.log(MESSAGE)</script>
</code></pre>
<p>Or by using the window object:</p>
<pre><code class="language-js"><script>window.MESSAGE = 'Hello World' console.log(MESSAGE)</script>
</code></pre>
<p>There are some reasons you wanna do something like this, however, always be careful when you do it.</p>
<h3>Nesting scopes</h3>
<p>it is possible to nest scopes, meaning to create a scope within another scope, and its a very common practice. Simply by adding an if statement inside a function we are doing this. So let’s see an example:</p>
<pre><code class="language-js">function nestedScopes() {
const message = 'Hello World!'
if (true) {
const fromIf = 'Hello If Purple!'
console.log(message) // Hello World!
}
console.log(fromIf) // ReferenceError: fromIf is not defined
}
nestedScopes()
</code></pre>
<h3>Lexical Scope</h3>
<p>In a way, we already made use of lexical scope, though we didn’t know about it. Lexical scope simply means that the children scopes have access to the variables defined in outer scopes.</p>
<pre><code class="language-js">function outerScope() {
var name = 'Irene'
function innerScope() {
console.log(name) // 'Irene'
}
return innerScope
}
const inner = outerScope()
inner()
</code></pre>
<p>That looks stranger than what it is, so let’s explain it. The function outerScope declares a variable name with value Juan and a function named innerScope. The later does not declare any variables for its own scope but makes use of the variable name declared in the outer function scope.</p>
<p>When outerScope() gets called it returns a reference to the innerScope function, which is later called from the outermost scope. When reading this code for the first time you may be confused as to why innerScope would console.log the value Juan as we are calling it from the global scope, or module scope, where name is not declared.
The reason why this works is thanks to JavaScript closures.</p>
<h3>Hoisting</h3>
<p>Hoisting in terms of JavaScript means that a variable is created in memory during the compile phase, and thus they can actually be used before they are actually declared. Sounds super confusing, let’s better see it in code.</p>
<pre><code class="language-js">function displayName(name) {
console.log(name)
}
displayName('Irene')
//***********************
// Outputs
//***********************
// 'Irene'
</code></pre>
<p>but what would you think of the following:</p>
<pre><code class="language-js">hoistedDisplayName('Irene')
function hoistedDisplayName(name) {
console.log(name)
}
//***********************
// Outputs
//***********************
// 'Irene'
</code></pre>
<p>👉 since the function is assigned to memory before the code actually runs, the function hoistedDisplayName is available before its actual definition, at least in terms of code lines.</p>
<p>👉 Functions have this particular property, but also do variables declared with var. Let’s see an example:</p>
<pre><code class="language-js">console.log(x8) // undefined
var x8 = 'Hello World!'
</code></pre>
<p>The fact that the variable is “created” before its actual definition in the code doesn’t mean that its value is already assigned, this is why when we do the console.log(x8) we don’t get an error saying that the variable is not declared, but rather the variable has value undefined. Very interesting, but what happens if we use let or const? Remember in our table they don’t share this property.</p>
<pre><code class="language-js">console.log(x9) // Cannot access 'x9' before initialization
const x9 = 'Hello World!'
</code></pre>
<p>It threw an error.</p>
<p>Hoisting is a lesser-known property of JavaScript variables, but it’s also an important one. Make sure you understand the differences, it is important for your code, and it may be a topic for an interview question.</p>
<h3>Reassignment of variables</h3>
<p>This topic covers specifically variables declared with the keyword const. A variable declared with const cannot be reassigned, meaning that we can’t change its value for a new one, but there’s a trick. Let’s see some examples:</p>
<pre><code class="language-js">const c1 = 'hello world!'
c1 = 'Hello World' // TypeError: Assignment to constant variable.
</code></pre>
<p>As expected, we can’t change the value of a constant, or can we?</p>
<pre><code class="language-js">const c2 = { name: 'Irene' }
console.log(c2.name) // 'Irene'
c2.name = 'Daniel'
console.log(c2.name) // 'Daniel'
</code></pre>
<p>Did we just change the value of a const value? The short answer is NO. Our constant c2 references an object with a property name. c2 is a reference to that object, that’s its value. When we do c2.name we are really taking the pointer to the c2 object and accessing the property from there. What we are changing when we do c2.name is the value of the property name in the object, but not the reference stored in c2, and thus c2 remained constant though the property value is now different.
what happens when we actually try to update the value differently:</p>
<pre><code class="language-js">const c3 = { name: 'Irene' }
console.log(c3.name) // 'Irene'
c3 = { name: 'Daniel' } // TypeError: Assignment to constant variable.
console.log(c3.name)
</code></pre>
<p>Even though the object looks the same, we are actually creating a new object { name: 'Daniel' } and trying to assign that new object to c3, but we can’t as it was declared as constant.</p>]]></content:encoded>
</item>
<item>
<title><![CDATA[React Hooks 🤔🎣]]></title>
<link>http://irenaapp.de//blog-react-post-hooks/</link>
<guid>http://irenaapp.de//blog-react-post-hooks/</guid>
<pubDate>Sun, 08 Nov 2020 23:14:21 GMT</pubDate>
<description><![CDATA[Hooks 🎣 API 👉 The additional API that lets you use state and other features in React without writing a class is called Hooks. What Are…]]></description>
<content:encoded><![CDATA[<h3>Hooks 🎣 API</h3>
<p>👉 The additional API that lets you use state and other features in React without writing a class is called Hooks.</p>
<h3>What Are React Hooks?</h3>
<p>React Hooks are in-built functions that allow React developers to use state and lifecycle methods inside functional components, they also work together with existing code, so they can easily be adopted into a codebase. The way Hooks were pitched to the public was that they allow developers to use state in functional components but under the hood, Hooks are much more powerful than that. They allow React Developers to enjoy the following benefits:</p>
<p>👉 Improved code reuse;</p>
<p>👉 Better code composition;</p>
<p>👉 Better defaults;</p>
<p>👉 Sharing non-visual logic with the use of custom hooks;</p>
<p>👉 Flexibility in moving up and down the components tree.</p>
<p>👉 Hooks are backwards-compatible.</p>
<p>With React Hooks, we have the power to use functional components for almost everything we need to do from just rendering UI to also handling state and also logic — which is pretty neat.
We know that components and top-down data flow help us organize a large UI into small, independent, reusable pieces. However, we often can’t break complex components down any further because the logic is stateful and can’t be extracted to a function or another component.</p>
<p>These cases are very common and include animations, form handling, connecting to external data sources, and many other things we want to do from our components. When we try to solve these use cases with components alone, we usually end up with:
Huge components that are hard to refactor and test.
Duplicated logic between different components and lifecycle methods.
Complex patterns like render props and higher-order componentHooks let us organize the logic inside a component into reusable isolated units.</p>
<p>Hooks apply the React philosophy (explicit data flow and composition) inside a component, rather than just between the components.</p>
<h3>What Are Hooks? 🤔</h3>
<p>To understand Hooks, we need to take a step back and think about code reuse.
Today, there are a lot of ways to reuse logic in React apps. We can write simple functions and call them to calculate something. We can also write components (which themselves could be functions or classes). Components are more powerful, but they have to render some UI. This makes them inconvenient for sharing non-visual logic. This is how we end up with complex patterns like render props and higher-order components.</p>
<p>Functions seem to be a perfect mechanism for code reuse. Moving logic between functions takes the least amount of effort. However, functions can’t have local React state inside them. You can’t extract behavior like “watch window size and update the state” or “animate a value over time” from a class component without restructuring your code or introducing an abstraction like Observables. Both approaches hurt the simplicity that we like about React.
Hooks solve exactly that problem. Hooks let you use React features (like state) from a function — by doing a single function call. React provides a few built-in Hooks exposing the “building blocks” of React: state, lifecycle, and context.</p>
<p>Since Hooks are regular JavaScript functions, you can combine built-in Hooks provided by React into your own “custom Hooks”.</p>
<p>👉 React Hooks enable us to write React applications with only function components. Thus, there is no need to use class components anymore.</p>
<h3>Unnecessary Component Refactorings:</h3>
<p>Function components with React Hooks prevent unnecessary component refactorings. Previously, only React class components were used for local state management and lifecycle methods. The latter have been essential for introducing side-effects, such as listeners or data fetching, in React class components. The following shows a React class component with state management:</p>
<pre><code class="language-js">import React, { Component } from 'react'
class Counter extends Component {
constructor(props) {
super(props)
this.state = {
count: 0,
}
}
render() {
return (
<div>
<p>You clicked {this.state.count} times</p>
<button onClick={() => this.setState({ count: this.state.count + 1 })}>
Click me
</button>
</div>
)
}
}
export default Counter
</code></pre>
<p>👉 So in short React Hooks let you use state and side effects in a functional components, something what was not possible before.</p>
<p>Before React Hooks were introduced to the world, this would be your workflow:</p>
<p>👉 create a functional (stateless) component</p>
<p>👉 ealise that you need to manage an internal state of this component</p>
<p>👉 rewrite this component into a class component</p>
<p>👉 happily manage components state</p>
<p>Now with React Hooks it looks much more streamlined:</p>
<p>👉 create a functional component</p>
<p>👉 happily manage components state</p>
<p>React Hooks let you manage the state and react to state changes in functional components.</p>
<p>Now lets explore the most common state management use cases in React components.</p>
<p>How to manage state with React Hooks?
Imagine that we have a simple React component that needs to be either collapsed or expanded.</p>
<pre><code class="language-js">import React from 'react'
const Collapsible = () => {
return (
<div className="isExpanded">
<h1>Item title</h1>
...
</div>
)
}
</code></pre>
<p>We would need to rewrite this into a class component if there were no React Hooks.</p>
<p>Luckily we have useState React Hook.</p>
<p>📌 State Hook</p>
<pre><code class="language-js">import React, { useState } from 'react'
const Collapsible = () => {
const [state, setState] = useState(false)
return (
<div className={state ? 'isExpanded' : null}>
<h1>Item title</h1>
...
</div>
)
}
</code></pre>
<p>We are importing <code>useState</code> from React and then creating a default state with the value of false.</p>
<p>Then we have access to the state variable and can render a css class when required.</p>
<p>If we wanted our component to be expanded by default we would set it to true by default.</p>
<p><code>state</code> and <code>setState</code> names are customisable names, you could call them whatever you like. color, setColor or user, setUser would do the same thing.</p>
<p>You get the point of sticking to a clear naming here.</p>
<p>state is the name of the stored variable and setState is a function that updates the value of this variable.</p>
<p>To change the value we could add onClick event to the h1 and toggle the value to the opposite true or false.</p>
<pre><code class="language-js">
import React, { useState } from 'react';
const Collapsible = () => {
const [state, setState] = useState(false);
return (
<div className={state ? 'isExpanded' : null}>
<h1 onClick={() => setState(!state)}>Item title</h1>
...
</div>
)
</code></pre>
<p>Now we are managing the internal state of our component using the useState React Hook.</p>
<p>You are not limited to a single value for your state, you can store objects, arrays or even nested objects.</p>
<p>Here is an example of a property object being stored in the state.</p>
<pre><code class="language-js">const [property, setProperty] = useState({
name: 'Hotel Filadelfia',
id: 'hh526',
location: 'Gert Street',
})
</code></pre>
<h3>How to fetch data with React Hooks?</h3>
<p>Another React Hook that you will need to master is useEffect().</p>
<p>It hooks into your React component in the same way as componentDidMount, componentDidUpdate, and componentWillUnmount used to.</p>
<pre><code class="language-js">import React, { useState, useEffect } from 'react'
const TopGames = () => {
const [games, setGames] = useState([])
useEffect(() => {
fetch('https://bgg-json.azurewebsites.net/hot')
.then((response) => response.json())
.then((data) => setGames(data))
})
return (
<div>
{games.map((game) => (
<p>{game.title}</p>
))}
</div>
)
}
</code></pre>
<p>We are importing useEffect React hook and then inside of it we are:</p>
<p>fetching data from an external API and
saving the response into a local state variable called games
The problem with the above code is that it would create an infinite loop!</p>
<p>The component mounts, we fetch data, the state gets updated, the components updates, we fetch data…and this continues.</p>
<p>By default useEffect() runs on the first render and on every update.</p>
<h3>👉 How to fix the infinite loop inside of useEffect hook ? 🤔</h3>
<p>To make the fetch call only once, we need to supply an empty array as the second parameter.</p>
<pre><code class="language-js">useEffect(() => {
fetch('https://bgg-json.azurewebsites.net/hot')
.then((response) => response.json())
.then((data) => setGames(data))
}, [])
</code></pre>
<p>This empty array tells React to run the function inside of it only after the first render, not on update.</p>
<p>In another example we could include a searchTerm dependency. This would make sure that the fetch call only happens when the searchTerm variable is updated.</p>
<pre><code class="language-js">useEffect(() => {
fetch(`https://someurl.com/api/${searchTerm}`)
.then((response) => response.json())
.then((data) => setGames(data))
}, [searchTerm])
</code></pre>
<p><code>searchTerm</code> is now a dependency for this side effect and unless searchTerm is updated, the fetch call would not run.</p>
<p>I have mentioned mount and update, but where is the <code>componentWillUnmount()</code>?</p>
<p>If your effect returns a function, it will be executed when it is a time for the component to be unmounted.</p>
<pre><code class="language-js">useEffect(() => {
// do something here first
// then console.log when unmouting
return () => {
console.log('unmounting now')
}
}, [])
</code></pre>
<p>This will simply console.log every-time this component gets removed from the DOM.</p>
<h3>Reference</h3>
<p><a href="https://reactjs.org/docs/hooks-reference.html#usereducer">React Hooks API </a></p>]]></content:encoded>
</item>
<item>
<title><![CDATA[Modules in JavaScript 🤔]]></title>
<link>http://irenaapp.de//blog-javascript-post/</link>
<guid>http://irenaapp.de//blog-javascript-post/</guid>
<pubDate>Thu, 29 Oct 2020 23:14:21 GMT</pubDate>
<description><![CDATA[What are Modules in JavaScript? 🤔 The Module Pattern is one of the important patterns in JavaScript. It is a commonly used Design Pattern…]]></description>
<content:encoded><![CDATA[<p>What are Modules in JavaScript? 🤔</p>
<p>The Module Pattern is one of the important patterns in JavaScript. It is a commonly used Design Pattern which is used to wrap a set of variables and functions together in a single scope.
It is essentially a piece of code written in a file that exposes a public API for other files to call and use. Just like regular Web APIs, modules enable developers to share an executable piece of code that accepts and returns values.</p>
<p>A module is just a file. One script is one module.</p>
<p>Modules can load each other and use special directives export and import to interchange functionality, call functions of one module from another one:</p>
<p>👉 <code>export</code> keyword labels variables and functions that should be accessible from outside the current module.</p>
<p>👉 <code>import</code> allows the import of functionality from other modules.
For instance, if we have a file sayHi.js exporting a function:</p>
<pre><code class="language-js">// 📁 👋sayHello.js
export function sayHello(user) {
alert(`Hello, ${user}!`);
}
</code></pre>
<pre><code class="language-js">// 📁 main.js
import {sayHi} from './sayHello.js';
alert(sayHi); // function...
sayHi('Irene'); // Hello, Irene!
</code></pre>
<p>👉 It is used to define objects and specify the variables and the functions that can be accessed from outside the scope of the function. We expose certain properties and function as public and can also restrict the scope of properties and functions within the object itself, making them private. This means that those variables cannot be accessed outside the scope of the function. We can achieve data hiding an abstraction using this pattern in the JavaScript.</p>
<h4>The benefits of using modules</h4>
<p>A modular approach will give your project the following features:</p>
<p><strong>Organization:</strong> Allows you to organize your code into small file chunks, with each file responsible for one job.</p>
<p><strong>Abstraction:</strong> Hides the implementation detail so you don’t need to understand how the code runs.</p>
<p><strong>Encapsulation:</strong> Just like you can expose a piece of code from a file, you can also hide / protect another piece of code from public access.</p>
<p><strong>Reusability:</strong> By exposing a piece of code that has accepts input and returns output, your code becomes a processing machine that can be reused by other pieces of code again and again.</p>
<h3>Understanding <strong>import</strong> & <strong>export</strong></h3>
<p>The <strong>import and export statements</strong> are one of the most crucial features of JavaScript ES6. It allows you to import and export JavaScript classes, functions, components, constants, any other variables between one JavaScript file and another.</p>
<p>This feature allows you to organize your JavaScript code into small, bite-size files. Making it easier to share, improve, manage, and debug your code as the development phase requires.</p>
<h4>How JavaScript export works 🤔 ?</h4>
<p>You can use a JavaScript export statement to export any JavaScript variable, function, or class. There is no limit to how many times you can export modules in one JavaScript file:</p>
<pre><code class="language-js">// example.js
export const user = 'Irene'
export let days = ['Monday', 'Tuesday', 'Wednesday']
export var countries = ['Bulgaria', 'Germany']
export function sayHi() {
console.log('Hello World!')
}
export const greet = name => {
console.log('Hello ' + name + '!')
}
export class User {
constructor(username){
this.username = username
}
}
</code></pre>
<p>All of these exports are valid.</p>
<h4>Multiple exports in a separate line</h4>
<p>The example above can be used to export multiple modules, but you can also export modules in a separate line by using the <code>export { .., .., .. } </code>syntax:</p>
<pre><code class="language-js">const user = 'Irene'
let days = ['Monday', 'Tuesday', 'Wednesday']
var countries = ['Bulgaria', 'Germany']
function sayHi() {
console.log('Hello World!')
}
const greet = name => {
console.log('Hello ' + name + '!')
}
class User {
constructor(username){
this.username = username
}
}
export {user, days, countries, sayHi, greet, User}
</code></pre>
<p>🛑 <strong>Notice how <code>user</code> and <code>User</code> could be used in one file without any error. JavaScript is case-sensitive, so it treats them as separate variables.</strong></p>
<h4>How JavaScript <strong>import</strong> works</h4>
<p>There are multiple ways to import a module in JavaScript. First, you can import specific modules by using the <code>import { .. } from .. </code>syntax:</p>
<pre><code class="language-js">import { user, days, countries } from './example'
</code></pre>
<p>The <code>from</code> keyword will tell JavaScript which file to look for the modules. Alternatively, you can import code and run it immediately by omitting the variable name and directly importing the file:</p>
<pre><code class="language-js">import './example'
sayHi();
</code></pre>
<p>Since the entire example.js code is executed with the import statement, you can call the <code>sayHi()</code> function immediately after that.</p>
<h3>Named export and import variables</h3>
<p>You can rename exported variables with the as keyword:</p>
<pre><code class="language-js">export { greet as greetings, user as myUser }
// you need to import with the new names
import { greetings, myUser } from './example'
</code></pre>
<p>And the same can be done with imports:</p>
<pre><code class="language-js">export { greet, user }
import { greet as greetings, user as myUser } from './example'
</code></pre>
<h4>Default export and import</h4>
<p>When you have only one module to export, you can use the export default statement:</p>
<pre><code class="language-js">export default class User {
constructor(username){
this.username = username
}
}
// or
class User {
constructor(username){
this.username = username
}
}
export default User
</code></pre>
<p>Unlike regular imports, a default import doesn’t use curly braces {} to wrap its modules:</p>
<pre><code class="language-js">import User from './example'
Instead of using the default keyword, default import simply write a variable name followed by from statement. Also, the variable name you declared for default import doesn’t need to match the export default variable name:
class User {
constructor(username){
this.username = username
}
}
export default User
// can be imported like this
import usr from './example'
</code></pre>
<p>The example above will be understood as import User as usr by JavaScript.</p>
<h3>@ symbol in JavaScript import statements</h3>
<p>As you code and collaborate with others through GitHub and any other medium, you might find some open source code using @ symbol in their import .. from .. syntax like this:</p>
<pre><code class="language-js">import Button from '@/components/Button'
// or
import Button from '~/components/Button'
</code></pre>
<p>The <strong>@ and ~ symbols</strong> are custom module loaders that are not part of JavaScript standard specification. Most likely, your project has a configuration file that can understand the symbols when you compile your code (usually through Babel or Webpack).</p>
<p>For example, babel-plugin-root-import treats the symbol as the root path, so you can write <code>@/components </code> instead of <code> ../../components</code>.</p>
<p>Note that this is different from NPM scoped packages, which also use <code>@</code> before the package name</p>
<p>RECAP</p>
<p>👉 In JavaScript, you can <strong>export modules in three different ways</strong>:</p>
<p>by placing the export statement before the module: <code>export const .. </code>syntax</p>
<p>Or in a separate line: <code>export { a, b, c}</code></p>
<p>You can also specify a default export with <code>export default ..</code></p>
<p>And named export with <code>export {xyz as abc}</code></p>
<p>👉 Then you can also import these modules as:</p>
<p>An import all with <code>import * as x from .. </code> syntax</p>
<p>A default import with <code>import x from ..</code></p>
<p>Multiple import with <code>import {x, y, z} from ..</code></p>
<p>Named import with <code>import { x as c } from ..</code></p>
<p>Run import code immediately with <code>import 'x'</code></p>
<p>JavaScript is <strong>case-sensitive</strong>, so you might have <code>x</code> is not defined error if you have a mismatch between your <strong>import</strong> and <strong>export</strong> statement.</p>
<p>🌴</p>]]></content:encoded>
</item>
<item>
<title><![CDATA[Node/Express App]]></title>
<link>http://irenaapp.de//blog-node-express/</link>
<guid>http://irenaapp.de//blog-node-express/</guid>
<pubDate>Thu, 10 Sep 2020 23:19:51 GMT</pubDate>
<description><![CDATA[Authentication in Express.js - simple app Introduction In this article, we are going to make a simple app to demonstrate how you can handle…]]></description>
<content:encoded><![CDATA[<h3>Authentication in Express.js - simple app</h3>
<h3>Introduction</h3>
<p>In this article, we are going to make a simple app to demonstrate how you can handle authentication in Express.js. Since we will be using some basic ES6 syntaxes and the Bootstrap framework for UI design, it might help if you have some basic knowledge about those technologies.</p>
<h3>Project Setup</h3>
<p>First, let's create a new folder called, say, simple-web-app. Using the terminal, we'll navigate to that folder and create a skeleton Node.js project:</p>
<pre><code class="language-bash">$ npm init
</code></pre>
<p>Now, we can install Express as well:</p>
<pre><code class="language-bash">$ npm install --save express
</code></pre>
<p>To keep things simple, a <strong>server-side</strong> rendering engine called <strong>Handlebars</strong> will be used. This engine will render the HTML pages on the server side, due to which, it won't be needing any other fron-tend framework such as Angular or React.</p>
<p>Let's go ahead and install express-handlebars:</p>
<pre><code class="language-bash">\$ npm install --save express-handlebars
</code></pre>
<p>I'll also be using two other Express middleware packages (body-parser and cookie-parser) to parse HTTP request bodies and parse the required cookies for authentication:</p>
<pre><code class="language-bash">$ npm install --save body-parser cookie-parser
</code></pre>
<h3>Implementation</h3>
<p>The application will contain a "protected" page that only logged in users can visit, otherwise, they'll be redirected to the home page - prompting them to either log in or register.</p>
<p>To get started, let's import the libraries we've previously installed:</p>
<pre><code class="language-js">const express = require('express')
const exphbs = require('express-handlebars')
const cookieParser = require('cookie-parser')
const bodyParser = require('body-parser')
</code></pre>
<p>I will be using the Node's native <strong>crypto</strong> module for password hashing and to generate an authentication token - this will be elaborated a bit later in the article.</p>
<p>Next, let's create a simple Express app and configure the middleware we've imported, alongside the Handlebars engine:</p>
<pre><code class="language-js">const app = express()
// To support URL-encoded bodies
app.use(bodyParser.urlencoded({ extended: true }))
// To parse cookies from the HTTP Request
app.use(cookieParser())
app.engine(
'hbs',
exphbs({
extname: '.hbs',
})
)
app.set('view engine', 'hbs')
// Our requests handlers will be implemented here...
app.listen(3000)
</code></pre>
<p>👉 By default in Handlebars, the template extension should be .handlebars. As you can see in this code we have configured our handlebars template engine to support files with the .hbs shorter extension. Now let's create a few template files:</p>
<p><img src="photo.png" alt=""></p>
<p>The layouts folder inside the view folder will hold your main layout, which will provide the base HTML for other templates.</p>
<p>Let's create the main.hbs, our main wrapper page:</p>
<pre><code class="language-html"><!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta http-equiv="X-UA-Compatible" content="ie=edge" />
<title>Document</title>
<link
rel="stylesheet"
href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css"
/>
</head>
<body>
<div class="container">
{{{body}}}
</div>
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"></script>
</body>
</html>
</code></pre>
<p>Other templates will render inside the {{{body}}} tag of this template. We have the HTML boilerplate and the required CSS and JS files for Bootstrap imported in this layout.</p>
<p>With our main wrapper done, let's create the <code>home.hbs</code> page, where users will be prompted to log in or register:</p>
<pre><code class="language-js"><nav class="navbar navbar-expand-lg navbar-light bg-light">
<a class="navbar-brand" href="#">Simple Authentication App</a>
</nav>
<div style="margin-top: 30px">
<a class="btn btn-primary btn-lg active" href="/login">Login</a>
<a class="btn btn-primary btn-lg active" href="/register">Register</a>
</div>
</code></pre>
<p>Then let's create a request handler to the path root path (/) to render the home template.</p>
<pre><code class="language-js">app.get('/', function (req, res) {
res.render('home')
})
</code></pre>
<p>Let's start our app up and navigate to <code>http://localhost:3000</code>:</p>
<h3>Account Registration</h3>
<p>The information about an account is collected through a registration.hbs page:</p>
<pre><code class="language-html"><div class="row justify-content-md-center" style="margin-top: 30px">
<div class="col-md-4">
{{#if message}}
<div class="alert {{messageClass}}" role="alert">
{{message}}
</div>
{{/if}}
<form method="POST" action="/register">
<div class="form-group">
<label for="firstNameInput">First Name</label>
<input
name="firstName"
type="text"
class="form-control"
id="firstNameInput"
/>
</div>
<div class="form-group">
<label for="lastNameInput">Last Name</label>
<input
name="firstName"
type="text"
class="form-control"
id="lastNameInput"
/>
</div>
<div class="form-group">
<label for="emailInput">Email address</label>
<input
name="email"
type="email"
class="form-control"
id="emailInput"
placeholder="Enter email"
/>
</div>
<div class="form-group">
<label for="passwordInput">Password</label>
<input
name="password"
type="password"
class="form-control"
id="passwordInput"
placeholder="Password"
/>
</div>
<div class="form-group">
<label for="confirmPasswordInput">Confirm Password</label>
<input
name="confirmPassword"
type="password"
class="form-control"
id="confirmPasswordInput"
placeholder="Re-enter your password here"
/>
</div>
<button type="submit" class="btn btn-primary">Login</button>
</form>
</div>
</div>
</code></pre>
<p>In this template, we have created a form with registration fields of the user which is the First Name, Last Name, Email Address, Password and Confirm Password and set our action as the /register route. Also, we have a message field in which we will display error and success messages for an example if passwords do not match, etc.</p>
<p>Let's create a request handle to render the registration template when the user visit <a href="http://localhost:3000/register">http://localhost:3000/register</a>:</p>
<pre><code class="language-js">app.get('/register', (req, res) => {
res.render('register')
})
</code></pre>
<p>Due to security concerns, it is a good practice to hash the password with a strong hashing algorithm like SHA256. By hashing passwords, we make sure that even if our password database might be compromised, the passwords aren't simply sitting there in plain sight in text format.</p>
<p>👉 An even better method than just simple hashing is to use salt, like with the bcrypt algorithm. For more information on securing authentication, check out Implementing User Authentication the Right Way. In this article, however, we'll keep things a bit simpler.</p>
<pre><code class="language-js">const crypto = require('crypto')
const getHashedPassword = (password) => {
const sha256 = crypto.createHash('sha256')
const hash = sha256.update(password).digest('base64')
return hash
}
</code></pre>
<p>When the user submits the registration form, a POST request will be sent to the /register path.</p>
<p>That being said, we now need to handle that request with the information from the form and persist our newly created user. Typically, this is done by persisting the user in a database, but for the sake of simplicity, we'll store users in a JavaScript array.</p>
<p>Since each server restart will reinitialize the array, we'll hardcode a user for testing purposes to be initialized every time:</p>
<pre><code class="language-js">const users = [
// This user is added to the array to avoid creating a new user on each restart
{
firstName: 'John',
lastName: 'Doe',
email: 'johndoe@email.com',
// This is the SHA256 hash for value of `password`
password: 'XohImNooBHFR0OVvjcYpJ3NgPQ1qq73WKhHvch0VQtg=',
},
]
app.post('/register', (req, res) => {
const { email, firstName, lastName, password, confirmPassword } = req.body
// Check if the password and confirm password fields match
if (password === confirmPassword) {
// Check if user with the same email is also registered
if (users.find((user) => user.email === email)) {
res.render('register', {
message: 'User already registered.',
messageClass: 'alert-danger',
})
return
}
const hashedPassword = getHashedPassword(password)
// Store user into the database if you are using one
users.push({
firstName,
lastName,
email,
password: hashedPassword,
})
res.render('login', {
message: 'Registration Complete. Please login to continue.',
messageClass: 'alert-success',
})
} else {
res.render('register', {
message: 'Password does not match.',
messageClass: 'alert-danger',
})
}
})
</code></pre>
<p>The received email, firstName, lastName, password, and confirmPassword are validated - passwords match, email isn't already registered, etc.</p>
<p>If each validation is successful we hash the password and store information inside the array and redirect the user to the login page. Otherwise, we will re-render the registration page with the error message.</p>
<p>Now, let's visit the /register endpoint to validate that it's working correctly:</p>
<h3>Account Login</h3>
<p>With registration out of the way, we can implement the login functionality. Let's start by making the login.hbs page:</p>
<pre><code class="language-html"><div class="row justify-content-md-center" style="margin-top: 100px">
<div class="col-md-6">
{{#if message}}
<div class="alert {{messageClass}}" role="alert">
{{message}}
</div>
{{/if}}
<form method="POST" action="/login">
<div class="form-group">
<label for="exampleInputEmail1">Email address</label>
<input
name="email"
type="email"
class="form-control"
id="exampleInputEmail1"
placeholder="Enter email"
/>
</div>
<div class="form-group">
<label for="exampleInputPassword1">Password</label>
<input
name="password"
type="password"
class="form-control"
id="exampleInputPassword1"
placeholder="Password"
/>
</div>
<button type="submit" class="btn btn-primary">Login</button>
</form>
</div>
</div>
</code></pre>
<p>And then, let's create a handler for that request as well:</p>
<pre><code class="language-js">app.get('/login', (req, res) => {
res.render('login')
})
</code></pre>
<p>This form will send a POST request to the <strong>/login</strong> when the user submits the form. Though, another thing we'll be doing is sending an authentication token for the login. This token will be used to identify the user and each time they send an HTTP request, this token will be sent as a cookie:</p>
<pre><code class="language-js">const generateAuthToken = () => {
return crypto.randomBytes(30).toString('hex')
}
</code></pre>
<p>With our helper method, we can create a request handler for the login page:</p>
<pre><code class="language-js">// This will hold the users and authToken related to users
const authTokens = {}
app.post('/login', (req, res) => {
const { email, password } = req.body
const hashedPassword = getHashedPassword(password)
const user = users.find((u) => {
return u.email === email && hashedPassword === u.password
})
if (user) {
const authToken = generateAuthToken()
// Store authentication token
authTokens[authToken] = user
// Setting the auth token in cookies
res.cookie('AuthToken', authToken)
// Redirect user to the protected page
res.redirect('/protected')
} else {
res.render('login', {
message: 'Invalid username or password',
messageClass: 'alert-danger',
})
}
})
</code></pre>
<p>👉 In this request handler, a <code>map</code> called <code>authTokens</code> is used to store authentication tokens as the key and the corresponding user as the value, which allows a simple token to user lookup. You can use a database like Redis, or really, any database to store these tokens - this map is used for simplicity.</p>
<p>Hitting the /login endpoint, we'll be greeted with:</p>
<p>We're not quite done yet though. We'll need to inject the user to the request by reading the authToken from the cookies upon receiving the login request. Above all the request handlers and below the cookie-parser middleware, let's create our own custom middleware for injecting users to the requests:</p>
<pre><code class="language-js">app.use((req, res, next) => {
// Get auth token from the cookies
const authToken = req.cookies['AuthToken']
// Inject the user to the request
req.user = authTokens[authToken]
next()
})
</code></pre>
<p>Now we can use req.user inside our request handlers to check if the user is authenticated via a token.</p>
<p>Finally, let's create a request handler to render the protected page - protected.hbs:</p>
<pre><code class="language-html"><nav class="navbar navbar-expand-lg navbar-light bg-light">
<a class="navbar-brand" href="#">Protected Page</a>
</nav>
<div>
<h2>This page is only visible to logged in users</h2>
</div>
</code></pre>
<p>And a request handler for the page:</p>
<pre><code class="language-js">app.get('/protected', (req, res) => {
if (req.user) {
res.render('protected')
} else {
res.render('login', {
message: 'Please login to continue',
messageClass: 'alert-danger',
})
}
})
</code></pre>
<p>As you can see, you can use req.user to check if the user is authenticated. If that object is empty, the user is not authenticated.</p>
<p>Another way to require authentication on routes is to implement it as middleware, which can then be applied to routes directly as they're defined with the app object:</p>
<pre><code class="language-js">const requireAuth = (req, res, next) => {
if (req.user) {
next()
} else {
res.render('login', {
message: 'Please login to continue',
messageClass: 'alert-danger',
})
}
}
app.get('/protected', requireAuth, (req, res) => {
res.render('protected')
})
</code></pre>
<p>Authorization strategies can also be implemented in this way by assigning roles to users and then checking for the correct permissions before the user accesses the page.</p>
<p>SumUp
User authentication in Express is pretty simple and straightforward. We've used Node's native crypto module to hash passwords of registered users as a basic safety feature, and created a protected page, visible only to users authenticated with a token.</p>
<p>The source code for this project can be found on GitHub.</p>
<p>Happy Coding!</p>]]></content:encoded>
</item>
<item>
<title><![CDATA[Conditionals & Loops]]></title>
<link>http://irenaapp.de//blog-javascript-lesson/</link>
<guid>http://irenaapp.de//blog-javascript-lesson/</guid>
<pubDate>Tue, 25 Aug 2020 23:19:51 GMT</pubDate>
<description><![CDATA[JavaScriptS | Conditionals and Loops 🤔 👉 Learning Goals You will be able to: 👉 Understand what statements are 👉 Understand why…]]></description>
<content:encoded><![CDATA[<h3>JavaScriptS | Conditionals and Loops 🤔</h3>
<h4>👉 Learning Goals</h4>
<p>You will be able to:</p>
<p>👉 Understand what statements are</p>
<p>👉 Understand why conditionals are necessary</p>
<p>👉 Understand and use the if..else statement</p>
<p>👉 Understand and use the switch statement</p>
<p>👉 Identify when it’s better to use switch over <code>if..else</code></p>
<p>👉 Understand why the loops and iterations are necessary</p>
<p>👉 Understand and use the <strong>while</strong> statement</p>
<p>👉 Understand and use the <strong>for</strong> statement</p>
<h3>Statements - general overview</h3>
<p>In JavaScript we write programs as a sequence of statements - so we can say that statements are code snippets that perform some action.
Some examples of statements are:</p>
<p><strong>if…else</strong>
<strong>switch</strong>
do…while
for
forEach
break
while</p>
<p>You can see the full list on the official <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements">MDN</a> site.</p>
<h3>👉 Conditional Statements</h3>
<p>During our life, we have to make decisions every day. What to wear for a job interview? Which train to take to get faster to work? What to buy for someones birthday? Some of them are more important than others, but they all have something in common: we have to decide what to do.</p>
<p>In programming, we have to make some decisions too. In our applications we will have to give more than one option to our user so they have to be able to choose - all this means we have to know how and when to use conditional statements.</p>
<p><strong>if..else</strong></p>
<p>👉 The if statement executes a statement if the specified condition is true. If the condition is false, another statement can be executed.</p>
<pre><code class="language-js">if (condition) {
// code to execute if the condition is true
}
</code></pre>
<p>We can add to our if an else statement, that will be executed just if the condition is not true.</p>
<blockquote>
<pre><code class="language-js">if (condition) {
// code to execute if the condition is true
} else {
// code to execute if the condition is false
}
</code></pre>
</blockquote>
<p><strong>Sometimes, we have more than one option or better saying, more than one condition to check before we make a decision and for this we use the <code>else if</code> statement.</strong>
Let’s create a simple example to see how the if ... else statement works. Let’s create a script to check if we have any kind of discount in the cinema. We will have a discount if we are younger than 16, or older than 65.</p>
<pre><code class="language-js">if (condition1) {
// code to execute if condition1 is true
} else if (condition2) {
// code to execute if condition2 is true
} else {
// code to execute if condition1 and condition2 are false
}
</code></pre>
<h3>Example</h3>
<p>👉 Let’s create a simple program to see how the <code>if ... else</code> statement works. Let’s create a script to check if we have any kind of discount in the cinema. We will have a discount if we are younger than 16, or older than 65.</p>
<pre><code class="language-js">const age = parseInt(prompt('Welcome to SineMax cinema. How old are you?'))
if (age <= 16) {
console.log('You have a teenager discount.')
} else if (age >= 65) {
console.log('You have a senior citizen discount :)')
} else {
console.log("Sorry, you don't have any discount :(")
}
</code></pre>
<p>Easy, right? Okay, let’s complicate it a little bit. We can have nested if..else statements. The syntax is as it follows:</p>
<pre><code class="language-js">if (condition) {
if (nestedCondition) {
// The code will be executed if
// condition === true && nestedCondition === true
} else {
// The code will be executed if
// condition === true && nestedCondition === false
}
} else {
// The code will be executed if
// condition === false
}
</code></pre>
<p>Let’s play around with two numbers to see how nested if works:</p>
<pre><code class="language-js">const number1 = parseInt(prompt('First number:'))
const number2 = parseInt(prompt('Second number:'))
if (number1 === number2) {
console.log('The numbers are equal.')
} else {
if (number1 > number2) {
console.log('Number 1 is bigger than number 2.')
} else {
console.log('Number 1 is smaller than number 2.')
}
}
</code></pre>
<p>🤖 Exercise: - Custom Greetings</p>
<p>Write an improved version of the ‘Good morning!’ program. Let’s ask the user in which language they want to see the message. You must have, at least, three different languages.</p>
<p>If the user wants the message in German, you have to log in the console “Guten Morgen!”.
If the user wants the message in French, you have to log in the console “Bonjour ”.
Finally, if we don’t have the indicated language, we will show “Good morning!”.
Use the <code>if…else</code> and <code>else if</code> statements we have just learned.</p>
<h4>Too many conditions</h4>
<p>Sometimes, an if statement can become very complicated. Let’s suppose we want to figure out the house of our favorite main character of Game of Thrones. We could do something like this:</p>
<pre><code class="language-js">const name = prompt('Favorite Game of Thrones main character:')
let house = ''
if (name === 'Khal Drogo') {
house = 'Dothraki Horselord'
} else if (name === 'Daenerys') {
house = 'Targaryen'
} else if (name === 'Jon Snow' || name === 'Sansa' || name === 'Arya') {
house = 'Stark'
} else if (name === 'Cersei' || name === 'Tyrion' || name === 'Ser Jaime') {
house = 'Lannister'
} else {
house = 'Other'
}
console.log(`Your favorite character is from the house ${house}.`)
</code></pre>
<p>This solution works but not everything that works is the correct/best solution. We have too many else if statements.</p>
<pre><code class="language-js">switch (expression) {
case value1:
// executed code when the expression === value1
break
case value2:
// executed code when the expression === value2
break
case value3:
// executed code when the expression === value3
break
default:
// executed code when none of the values match the expression
}
</code></pre>
<p>The switch statement helps us to do exactly the same thing we did previously in the “Game of Thrones” example. It evaluates an expression,or better saying - checks the condition and executes statements associated with that case.</p>
<p>Let’s change the previous Game of Thrones example to see how switch works. We will go step by step:</p>
<p>STEP 1 - Khal Drogo</p>
<pre><code class="language-js">const name = prompt('Favorite Game of Thrones main character:')
let house = ''
switch (name) {
case 'Khal Drogo':
house = 'Dothraki Horselord'
}
console.log(`Your favorite character is from the house ${house}.`)
</code></pre>
<p>If we pass “Khal Drogo” as the answer, we will get as a result “Your favorite character is from the house Dothraki Horselord”.</p>
<h5>STEP 2 - Daenerys</h5>
<pre><code class="language-js">const name = prompt('Favorite Game of Thrones main character:')
let house = ''
switch (name) {
case 'Khal Drogo':
house = 'Dothraki Horselord'
case 'Daenerys':
house = 'Targaryen'
}
console.log(`Your favorite character is from the house ${house}.`)
</code></pre>
<p>Now, if you introduce “Daenerys”, you will get as a result “Your favorite character is from the house Targaryen”. But… what happens if you say “Khal Drogo”? “Khal Drogo” is not from Targaryen house!</p>
<p>👉 We have to add a <strong>break statement at the end of each case clause.</strong> What is break for?</p>
<blockquote>
<p>break statement terminates the current switch statement => the current case.</p>
</blockquote>
<p>The problem we have right now is that we are running both case statements, and the second one sets the house variable to “Targaryen”. If we add the break statement at the end of each case, the problem will be solved.</p>
<pre><code class="language-js">const name = prompt('Favorite Game of Thrones main character:')
let house = ''
switch (name) {
case 'Khal Drogo':
house = 'Dothraki Horselord'
break
case 'Daenerys':
house = 'Targaryen'
break
}
console.log(`Your favorite character is from the house ${house}.`)
</code></pre>
<p>All right, this is much better.</p>
<p>STEP 3 - Stark House</p>
<p>Now we have a case with several options. Jon Snow, Arya and Sansa are from Stark House. What happens if we set the case expression like the following:</p>
<pre><code class="language-js">case "Jon Snow" || "Sansa" || "Arya"
</code></pre>
<p>Does it work for all the options? No, right? It just works with the first option. In this case, it just works as we expect with “Jon Snow”.</p>
<blockquote>
<p>We can’t have several options in the same case statement, but we can set the same code to execute for different case.</p>
</blockquote>
<p>Let’s take a look at how to do that:</p>
<pre><code class="language-js">const name = prompt('Favorite Game of Thrones main character:')
let house = ''
switch (name) {
case 'Khal Drogo':
house = 'Dothraki Horselord'
break
case 'Daenerys':
house = 'Targaryen'
break
case 'Jon Snow':
case 'Sansa':
case 'Arya':
house = 'Stark'
break
}
console.log(`Your favorite character is from the house ${house}.`)
</code></pre>
<p>🤖 Exercise:
Use the same technique to add the Lannister house to our script. Don’t forget to add the break statement to avoid conflicts between houses. We don’t want a house misunderstanding that will cause a war!</p>
<p>STEP 4 - Other characters</p>
<p>We all know that Game of Thrones is an entire world. We can’t consider all the characters here: it would take a lot of time, and we have more stuff to cover. So let’s create the last statement to consider all the other houses. We use the default statement to do that:</p>
<pre><code class="language-js">const name = prompt('Favorite Game of Thrones main character:')
let house = ''
switch (name) {
case 'Khal Drogo':
house = 'Dothraki Horselord'
break
case 'Daenerys':
house = 'Targaryen'
break
case 'Jon Snow':
case 'Sansa':
case 'Arya':
house = 'Stark'
break
default:
house = 'other'
}
console.log(`Your favorite character is from the house ${house}.`)
</code></pre>
<p>This is how switch works. Wait… we have forgotten the break in the default statement, right? Do you remember what the break statement does?</p>
<p>As we have seen, the break statement terminates the current switch statement and transfers our script just at the end of the switch statement. default is our last statement inside the switch, so it’s not necessary to add the break statement in this case.</p>
<h3>Loops & Iterations</h3>
<p>👉 In JavaScript, loops and iterations are used to execute repetitive tasks.</p>
<p>For example, if we want to print numbers from 1 to 100, we won’t type them all. We will use while or for statement to do that. They both offer us a quick and easy way to do something repeatedly.</p>
<pre><code class="language-js">while statement
while (condition) {
// code to be executed while the condition is true
}
</code></pre>
<p>while statement creates a loop that executes a specified code as long as the condition evaluates true.</p>
<p>Let’s print in the console the numbers from 0 to 100 with a while statement. The code is the following:</p>
<pre><code class="language-js">let i = 0
while (i <= 100) {
console.log(i)
i++ // this is the same as i = i + 1
}
</code></pre>
<blockquote>
<h4>👉 The script follows the following rules:</h4>
<ul>
<li>Check if the value of [i] is lower or equal than 100</li>
<li>If yes, print in the console the value of [i]</li>
<li>Increment the value of the [i] by 1</li>
<li>Again check if the value of [i] is lower or equal to 100 and as long as it is, executes these steps over and over again.</li>
</ul>
</blockquote>
<h3><code>do while statement</code></h3>
<h4>Summary</h4>
<p>We use <strong>boolean values (true or false)</strong> in the conditional statements like <code>if..else</code> or <code>switch</code>, and depending in the condition we know which block of code will execute.</p>
<p>If you are evaluating one condition and you have too many options to check, the best solution is to change the if..else statement for a switch statement.</p>
<p>Finally, we have learned how to iterate several times with two different statements, while and for.</p>
<h4>Resources</h4>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements">MDN - Statements and declarations</a></li>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators">MDN - Logical operators</a></li>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/if...else">MDN - if...else statement</a></li>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/switch">MDN - switch statement</a></li>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Loops_and_iteration#for_statement">MDN - for statement</a></li>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Loops_and_iteration#while_statement">MDN - while statement</a></li>
</ul>]]></content:encoded>
</item>
<item>
<title><![CDATA[DataBase - MongoDB]]></title>
<link>http://irenaapp.de//blog-db-mongodb-post/</link>
<guid>http://irenaapp.de//blog-db-mongodb-post/</guid>
<pubDate>Tue, 18 Aug 2020 23:19:51 GMT</pubDate>
<description><![CDATA[What is MongoDB ? 🤔🔨 MongoDB is a popular NoSQL database management system that stores data as BSON (binary JSON) documents. It's…]]></description>
<content:encoded><![CDATA[<h4>What is MongoDB ? 🤔🔨</h4>
<p>MongoDB is a popular NoSQL database management system that stores data as BSON (binary JSON) documents. It's frequently used for big data and real-time applications running at multiple different locations. Relative to the CAP theorem, MongoDB is a CP data store—it resolves network partitions by maintaining consistency, while compromising on availability.</p>
<p><strong>MongoDB is a single-master system—each replica set can have only one primary node that receives all the write operations.</strong> All other <strong>nodes in the same replica set are secondary nodes</strong> that replicate the primary node's operation log and apply it to their own data set. By default, clients also read from the primary node, but they can also specify a read preference that allows them to read from secondary nodes.</p>
<p>When the primary node becomes unavailable, the secondary node with the most recent operation log will be elected as the new primary node. Once all the other secondary nodes catch up with the new master, the cluster becomes available again. As clients can't make any write requests during this interval, the data remains consistent across the entire network.</p>
<p>🛑 What is the CAP theorem?</p>
<p>Have you ever seen an advertisement for a landscaper, house painter, or some other tradesperson that starts with the headline, “Cheap, Fast, and Good: Pick Two”?</p>
<p><img src="../images/cap-theorem.png" alt="CAP Theorem"></p>
<p>The <strong>CAP theorem</strong> applies a similar type of logic to distributed systems—namely, that a distributed system can deliver only two of three desired characteristics:</p>
<blockquote>
<p>👉 consistency - that reads are always up to date, which means any client making a request to the database will get the same view of data. Or - Every read receives the most recent writes or an error. For consistency, any read operation that begins after a write operation completes must return that value, or the result of a later write operation.</p>
<p>👉In a consistent system, once a client writes a value to any server and gets a response, it expects to get that value (or a fresher value) back from any server it reads from.</p>
</blockquote>
<blockquote>
<p>👉 availability - database requests always receive a response (when valid). Or - Every request received by a non-failing node in the system must result in a response. Whether you want to read or write you will get some response back.</p>
</blockquote>
<blockquote>
<p>👉 partition tolerance - that a network fault doesn’t prevent messaging between nodes.
The system continues to operate despite an arbitrary number of messages being dropped(or delayed) by the network between nodes. When a network is partitioned, all messages sent from nodes in one component of the partition to nodes in another component are lost.</p>
</blockquote>
<p><strong>CAP theorem states that it is impossible for a distributed system to simultaneously provide more than two out of the above three guarantees.</strong></p>
<p>🛑 All distributed system needs partition tolerance because no distributed system is safe from network failure. In presence of a partition tolerance, we can select one out of two options: <strong>Consistency and Availability.</strong></p>
<p>👉 ⚠️ CAP Theorem is frequently misunderstood that one has to choose two out of three guarantees all the times. In fact, one has to choose between Consistency and Availability only when there is a network partition or failure happens. In absence of network partition or network failures, both availability and consistency can be satisfied.</p>
<p>AP(Availability and Partition tolerance): When availability is chosen over consistency, the system is will always process the client request and try to return the most recent available version of the information even if it cannot guarantee it is up to date due to network partitioning.</p>
<p>CP(Consistency and Partition tolerance): When consistency is chosen over availability, the system will return an error or time-out if particular information cannot be updated to other nodes due to network partition or failures.
Database system designed with ACID guarantees (RDBMS) usually chooses consistency over availability whereas system Designed with BASE guarantees, chooses availability over consistency.</p>
<p>🛑 A distributed system is a network that stores data on more than one node (physical or virtual machines) at the same time. Because all cloud applications are distributed systems, it’s essential to understand the CAP theorem when designing a cloud app so that you can choose a data management system that delivers the characteristics your application needs most.</p>
<p>👉 In the context of distributed (NoSQL) databases, this means there is always going to be a trade-off between consistency and availability. This is because distributed systems are always necessarily partition tolerant (ie. it simply wouldn’t be a distributed database if it wasn’t partition tolerant.)</p>
<h3>CAP Theorem when making database decisions</h3>
<p>Although the CAP Theorem can feel quite abstract, it has practical, real-world consequences. From both a technical and business perspective the trade-offs will lead you to some very important questions. There are no right answers. Ultimately it will be all about the context in which your database is operating, the needs of the business, and the expectations and needs of users.</p>
<h4>Consider things like:</h4>
<ul>
<li>Is it important to avoid throwing up errors in the client?</li>
<li>Or are we willing to sacrifice the visible user experience to ensure consistency?</li>
<li>Is consistency an actual important part of the user’s experience</li>
<li>Or can we actually do what we want with a relational database and avoid the need for partition tolerance altogether?</li>
</ul>]]></content:encoded>
</item>
<item>
<title><![CDATA[Increment & Decrement in JavaScript]]></title>
<link>http://irenaapp.de//blog-js-increment-post/</link>
<guid>http://irenaapp.de//blog-js-increment-post/</guid>
<pubDate>Sat, 15 Aug 2020 23:19:51 GMT</pubDate>
<description><![CDATA[Overview of Increment and Decrement Operators in JavaScript The Increment and Decrement Operators are used to increase or decrease the value…]]></description>
<content:encoded><![CDATA[<p><strong>Overview of Increment and Decrement Operators in JavaScript</strong></p>
<p>The Increment and Decrement Operators are used to increase or decrease the value by 1.</p>
<p>For example:</p>
<p>Incremental operator <code>++</code> is used to increase the existing variable value by <code>1 (x = x + 1)</code>.</p>
<p>The decrement operator <code>– –</code> on the other hand is used to decrease or subtract the existing value by <code>1 (x = x – 1)</code>.</p>
<p><strong>JavaScript Prefix and Postfix</strong></p>
<p>If you observe the above syntax, we can assign the JavaScript increment and decrement operators either before operand or after the operand.</p>
<p>When <code>++</code> or <code>—</code>is used before operand like: <code>++x</code>, <code>–x</code> then we call it as prefix, if <code>++</code> or <code>—</code>is used after the operand like: <code>x++</code> or <code>x–</code> then we called it as <strong>postfix.</strong></p>
<p>Let’s explore the JavaScript <strong>prefix and postfix</strong></p>
<ol>
<li>++i (Pre increment): It will increment the value of i even before assigning it to the variable i.</li>
<li>i++ (Post-increment): The operator returns the variable value first (i.e, i value) then only i value will incremented by 1.</li>
<li>–i (Pre decrement): It decrements the value of i even before assigning it to the variable i.</li>
<li>i– (Post decrement): The JavaScript operator returns the variable value first (i.e., i value), then only i value decrements by 1.</li>
</ol>
<p><strong>Prefix and Postfix Example</strong></p>
<p>The <code>++</code> or <code>— —</code>can be applied both before and after the variable.
This is where it gets a bit tricky.</p>
<p>Syntax</p>
<pre><code class="language-js">Postfix Form: counter++
Prefix Form: ++counter
</code></pre>
<p>Although both forms increase the variable by 1, there is a difference:</p>
<p>🛑 The <strong>Postfix</strong> Form returns the original value of the variable, before the <strong>increment/decrement</strong></p>
<p>🛑 The <strong>Prefix</strong> Form returns the value after the <strong>increment/decrement</strong>.</p>
<p>This difference can be seen if we are using the returned value of the <strong>increment/decrement.</strong></p>
<p>Example</p>
<p>Prefix</p>
<pre><code class="language-js">let counter = 2
alert(++counter) // 3 incremented value has been returned
</code></pre>
<p>Postfix</p>
<pre><code class="language-js">let counter = 2
alert(counter++) // 2 Returns the original value prior to the increment
</code></pre>
<p>If we are using the value of the increment/decrement at a later point in time however, there is no difference between the forms.</p>
<p>Example</p>
<p>Prefix</p>
<pre><code class="language-js">let counter = 2
++counter // 3 The incremented value
alert(counter) // 3 Incremented value has been returned
</code></pre>
<p>Postfix</p>
<pre><code class="language-js">let counter = 2
counter++ // 2 The original value
alert(counter) // 3 Value has now been incremented and returns the new value
</code></pre>
<p>In the prefix version <code>(++i)</code>, the value of <code>i</code>is incremented, and the value of the expression is the <strong>new value of <code>i</code></strong>.</p>
<p>In the postfix version <code>(i++)</code>, the value of <code>i</code> is incremented, but the value of the expression is <strong>the original value of <code>i</code></strong>.</p>
<p>Let's analyze the following code line by line:</p>
<pre><code class="language-js">int i = 10; // (1)
int j = ++i; // (2)
int k = i++; // (3)
</code></pre>
<ol>
<li><code>i</code> is set to 10 (easy).</li>
<li>two things on this line:</li>
</ol>
<ul>
<li>i is incremented to 11.</li>
<li>The new value of i is copied into j. So j now equals 11.</li>
<li></li>
</ul>
<ol start="3">
<li>Two things on this line as well:</li>
</ol>
<ul>
<li><code>i</code> is incremented to 12.
The original value of <code>i</code>(which is 11) is copied into k. So k now equals 11.</li>
</ul>
<p>👉 So after running the code, i will be 12 but both j and k will be 11.</p>
<p>The same stuff holds for postfix and prefix versions of <code>--</code>.</p>
<p>Another example</p>
<pre><code class="language-js">let var1 = 5,
var2 = 5
// var1 is displayed
// Then, var1 is increased to 6
console.log(var1++)
// var2 is increased to 6
// Then, var2 is displayed
console.log(++var2)
// output of the program: 5,6
</code></pre>]]></content:encoded>
</item>
<item>
<title><![CDATA[Intro to Python ]]></title>
<link>http://irenaapp.de//blog-python-basics-post/</link>
<guid>http://irenaapp.de//blog-python-basics-post/</guid>
<pubDate>Sun, 09 Aug 2020 23:19:51 GMT</pubDate>
<description><![CDATA[Python Keywords Keywords are the reserved words in Python. We cannot use a keyword as a variable name, function name or any other identifier…]]></description>
<content:encoded><![CDATA[<h3>Python Keywords</h3>
<p>Keywords are the reserved words in Python.</p>
<p>We cannot use a keyword as a variable name, function name or any other <strong>identifier</strong>. They are used to define the syntax and structure of the Python language.</p>
<p>🛑 <strong>In Python, keywords are case sensitive.</strong></p>
<p>There are 33 keywords in Python 3.7. This number can vary slightly over the course of time.</p>
<p>All the keywords except True, False and None are in lowercase and they must be written as they are. The list of all the keywords is given below.</p>
<p>False | await | else | import |pass
None | break | except | in raise
True class finally is return
and continue for lambda try
as def from nonlocal while
assert del global not with
async elif if or yield</p>
<h4>Python Identifiers</h4>
<p>👉 <strong>An identifier is a name given to entities like class, functions, variables, etc. It helps to differentiate one entity from another.</strong></p>
<h4>Rules for writing identifiers</h4>
<p>Identifiers can be a combination of letters in lowercase (a to z) or uppercase (A to Z) or digits (0 to 9) or an underscore _. Names like myClass, var_1 and print_this_to_screen, all are valid example.
An identifier cannot start with a digit. 1variable is invalid, but variable1 is a valid name.
Keywords cannot be used as identifiers.</p>
<pre><code class="language-python">
global = 1
</code></pre>
<p>Output</p>
<pre><code class="language-python">
File "<interactive input>", line 1
global = 1
^
SyntaxError: invalid syntax
</code></pre>
<p>We cannot use special symbols like <strong><code>!, @, #, $, %</code></strong> etc. in our identifier.</p>
<pre><code class="language-python">
a@ = 0
</code></pre>
<p>basic python syntax</p>
<pre><code class="language-python">print('Irena')
name=input()
print('Irena ' + name)
</code></pre>
<h3>VARIABLES AND TYPES</h3>
<h4>Naming Variables</h4>
<p>🛑 <strong>Python variables can’t start with with a number.</strong> In general, they’re named all lower case, separated by underscores. Unlike other languages, that name their variables with camelCase.</p>
<p>You don’t want to name your variables the same as the types that we’ll be working with. For example don’t name your variables int, list, dict. Etc.</p>
<h3>Open The REPL</h3>
<p>Open the REPL from VS Code by opening the command palette (ctrl + shift + P on Windows, or cmd + shift + P on Mac) and selecting <strong>Python: Start REPL</strong></p>
<p>Any Python code that starts with the <code>>>></code>symbols indicates that it was typed into a <strong>REPL</strong>.</p>
<p>You can then use <code>ctrl +</code> `(backtick) to open and close the VS Code terminal on Mac, or ctrl + ‘ (single quote) on Windows. You won’t lose your work in the REPL unless you close VS Code.</p>
<h3>Variables</h3>
<p>Variables in Python allow us to store information and give it a label that we can use to retrieve that information later. 👉 <strong>We can use variables to store numbers, strings (a sequence of characters), or even more complex data types like lists and dictionaries.</strong></p>
<p><strong>We assign values to variables by putting the value to the right of an equal sign.</strong></p>
<p>👉 <strong>Because Python is a dynamic language, we don’t need to declare the type of the variables before we store data in them.</strong></p>
<p>That means that this is valid Python code:</p>
<pre><code class="language-python">> > > x = 42
> > > Unlike typed languages, the type of what’s contained in Python variables can change at any time.
</code></pre>
<p>For example, the below is perfectly valid Python code:</p>
<pre><code class="language-python"> x = 42
x = "hello"
Here, the value of the variable x changed from a number to a string.
</code></pre>
<p><strong>When creating variables, there are a few best practices you should follow.</strong></p>
<h3>Naming Variables</h3>
<p>👉 Convention says that numbers should be named in lower case, with whole words separated by underscores.</p>
<p>If you want to learn more about Python naming conventions look at <strong>PEP8</strong>.</p>
<p>👉 Because Python is a dynamic language and you don’t have type hints to explain what’s stored inside a variable while reading code, you should do your best naming your variables to describe what is stored inside of them.</p>
<p>It’s ok to be <strong>verbose</strong>. For example, <strong>n</strong> is a poor variable name, while <strong>numbers</strong> is a better one. <strong>If you’re storing a collection of items, name your variable as a plural.</strong></p>
<p>Learn more about great naming practices for dynamic types by watching this 30-minute talk by Brandon Rhodes.</p>
<h3>Naming Gotchas</h3>
<p>👉 There are some things that you can’t name your variables, such as and, if, True, or False. That’s because Python uses these names for program control structure.</p>
<p>🛑 You can’t start your variable name with a digit, although your variable name can end in a digit. Your variable name <strong>can’t contain</strong> special characters, such as **!, @, #, $, %**and more.</p>
<p>💣 <strong>Python will let you override built-in methods and types without a warning so don’t name your Python variables things like <code>list</code>, <code>str</code>, or <code>int</code>.</strong></p>
<p>If you notice your program behaving oddly and you can’t find the source of the bug, double check the list of built-in functions and built-in types to make sure that your variable names don’t conflict.</p>
<h3>Types</h3>
<p>Python has a very easy way of determining the type of something. It’s the <strong>type() function</strong>.</p>
<pre><code class="language-python"> num = 42
type(num)
class 'int'>
</code></pre>
<h3>No-Value, None, or Null Value</h3>
<p>There’s a special type in Python that signifies no value at all. In other languages, it might be called <strong>Null.</strong> In Python, it’s called <strong>None</strong>.</p>
<p>If you try to examine a variable on the <strong>REPL</strong> that’s been set to <strong>None</strong>, you won’t see any output. I will talk more about the None type in another post.</p>
<pre><code class="language-python">> > > x = None
> > > x
</code></pre>
<h3>NUMBERS</h3>
<p>First, open up the REPL.</p>
<p>Remember, you’ll learn best if you type.</p>
<p>👉 <strong>There are three different types of numbers in Python: int for Integer, Float, and Complex.</strong></p>
<pre><code class="language-python"># These are all integers
x = 4
y = -193394
z = 0
</code></pre>
<pre><code class="language-python"># These are all floats
x = 5.0
y = -3983.2
z = 0.
</code></pre>
<pre><code class="language-python"># This is a complex number
x = 42j
</code></pre>
<p>In Python, <strong>Integers and other simple data types are just objects under the hood.</strong> That means that you can create new ones by calling methods. You can provide either a number, or a string.</p>
<pre><code class="language-python">x = int(4)
y = int('4')
z = float(5.0)
</code></pre>
<p>Python also provides a decimal library, which has certain benefits over the float datatype. For more information, refer to the Python documentation.</p>
<h3>Mathematical Operations</h3>
<p>Numbers can be added together. If you add a float and an int, the resulting type will be a float.</p>
<p>If you divide two ints (integers), the result will be of type float.</p>
<h3>Boolean Types</h3>
<p>In Python, Booleans are of type bool. Surprisingly, the boolean types True and False are also numbers under the hood.</p>
<p><strong>True is 1 under the hood.</strong>
<strong>False is 0 under the hood.</strong></p>
<p>That means you can do silly things, like add two Boolean numbers together.</p>
<h3>STRINGS</h3>
<h4>Representing Strings</h4>
<p>👉 Strings in Python can be enclosed either with single quotes like 'hello' or double quotes, like "hello".</p>
<p><strong>Strings can also be concatenated (added together) using the + operator to combine an arbitrary number of Strings.</strong> For example:</p>
<pre><code class="language-python">1334
salutation = "Hello "
name = "Irene"
greeting = salutation + name
# The value of greeting will be "Hello Irene"
</code></pre>
<p>To use the same type of quote within a string, that quote needs to be escaped with a \ - backwards slash.</p>
<pre><code class="language-python">greeting = 'Hello, it\'s Irene'
</code></pre>
<p>Alternately, mixed quotes can be present in a Python string without escaping.</p>
<pre><code class="language-python"># Notice that the single quote ' is surrounded by
# double quotes, ""
greeting = "Hello, it's Irene"
</code></pre>
<p>Long multi-line strings can be represented in between """ (triple quotes), but the whitespace will be part of the string.</p>
<pre><code class="language-python">long_greeting = """
Greetings and salutations, dear Irene.
I'm superfluous with my words,
and require more space to say Hello!"
"""
</code></pre>
<h3>Printing Strings</h3>
<p>Strings can be printed out using the print() function in Python. While you’re working the REPL, you’ll see that variables are displayed for you. When you move on to writing standalone Python programs, that will no longer be the case.</p>
<p>To use the print() function, call it with a regular or formatted string.</p>
<pre><code class="language-python">>>> print("Hello")
Hello
>>> name = "Irene"
>>> print(name)
Irene
### String Formatting
</code></pre>
<p>There are several types of string formatting in Python.</p>
<p>If you’re using Python 3.7 and above (remember to check with python --version on the command line) you can use my favorite type of string formatting, and the one I’ll be using for the course called f-strings.</p>
<pre><code class="language-python">>>> name = "Irene"
>>> greeting = f"Hello, {name}"
>>> print(greeting)
Hello, Irene
</code></pre>
<p><strong>f-strings</strong> allow you to simply and easily reference variables in your code, and as a bonus, they’re much faster.</p>]]></content:encoded>
</item>
<item>
<title><![CDATA[React Context APIs]]></title>
<link>http://irenaapp.de//blog-js-practice/</link>
<guid>http://irenaapp.de//blog-js-practice/</guid>
<pubDate>Sun, 09 Aug 2020 23:19:51 GMT</pubDate>
<description><![CDATA[Context Apis React's Context API has become the state management tool of choice for many, often replacing Redux altogether.
React Context…]]></description>
<content:encoded><![CDATA[<h3>Context Apis</h3>
<p>React's Context API has become the state management tool of choice for many, often replacing Redux altogether.
React Context API is a way to essentially create global variables that can be passed around in a React app. This is the alternative to "prop drilling", or passing props from grandparent to parent to child, and so on. Context is often touted as a simpler, lighter solution to using Redux for state management.</p>
<h3>How to Create Context</h3>
<p>create Context, and call it UserContext. This will also give me UserContext.Provider and UserContext.Consumer. What these two components do is straightforward:</p>
<p><strong>Provider</strong>- The component that provides the value
<strong>Consumer</strong> - A component that is consuming the value
So I'll create it with React.createContext() in a new file called UserContext.js.</p>
<pre><code class="language-js">import React from 'react'
const UserContext = React.createContext()
export const UserProvider = UserContext.Provider
export const UserConsumer = UserContext.Consumer
export default UserContext
</code></pre>
<p>passing in an empty object value here to represent that I might be filling in this data later with an API call. You can pre-populate this with whatever data you want, in case you're not retrieving the data through an API.</p>
<pre><code class="language-js">React.createContext(true)
</code></pre>
<h3>Providing Context</h3>
<p>The provider always needs to exist as a wrapper around the parent element, no matter how you choose to consume the values. I'll wrap the entire App component in the Provider. I'm just creating some value (user) and passing it down as the Provider value prop.</p>
<pre><code class="language-js">import React from 'react'
import HomePage from './HomePage'
import { UserProvider } from './UserContext'
function App() {
const user = { name: 'Iren', loggedIn: true }
return (
<UserProvider value={user}>
<HomePage />
</UserProvider>
)
}
</code></pre>
<p>any child, grandchild, great-grandchild, and so on will have access to user as a prop. Unfortunately, retrieving that value is slightly more involved than simply getting it like you might with this.props or this.state.</p>
<h3>Consuming Context</h3>
<p>The way you provide Context is the same for class and functional components, but consuming it is a little different for both.</p>
<h3>Class component</h3>
<p>The most common way to access Context from a class component is via the static contextType. If you need the value from Context outside of render, or in a lifecycle method, you'll use it this way.</p>
<pre><code class="language-js">import React, { Component } from 'react'
import UserContext from './UserContext'
class HomePage extends Component {
static contextType = UserContext
componentDidMount() {
const user = this.context
console.log(user) // { name: 'Iren', loggedIn: true }
}
render() {
return <div>{user.name}</div>
}
}
</code></pre>
<p>The traditional way to retrieve Context values was by wrapping the child component in the Consumer. From there, you would be able to access the value prop as props. You may still see this, but it's more of a legacy way of accessing Context.</p>
<pre><code class="language-js">import React, { Component } from 'react'
import { UserConsumer } from './UserContext'
class HomePage extends Component {
render() {
return (
<UserConsumer>
{(props) => {
return <div>{props.name}</div>
}}
</UserConsumer>
)
}
}
</code></pre>
<h3>Functional component and Hooks</h3>
<p>For functional components, you'll use useContext, such as in the example below. This is the equivalent of static contextType.</p>
<pre><code class="language-js">import React, { useContext } from 'react'
import UserContext from './UserContext'
export const HomePage = () => {
const user = useContext(UserContext)
return <div>{user.name}</div>
}
</code></pre>
<h3>Updating Context</h3>
<p>Updating context is not much different than updating regular state. We can create a wrapper class that contains the state of Context and the means to update it.</p>
<pre><code class="language-js">import React, { Component } from 'react'
const UserContext = React.createContext()
class UserProvider extends Component {
// Context state
state = {
user: {},
}
// Method to update state
setUser = (user) => {
this.setState((prevState) => ({ user }))
}
render() {
const { children } = this.props
const { user } = this.state
const { setUser } = this
return (
<UserContext.Provider
value={{
user,
setUser,
}}
>
{children}
</UserContext.Provider>
)
}
}
export default UserContext
export { UserProvider }
</code></pre>
<p>👉 update and view the user from the Context method.</p>
<pre><code class="language-js">import React, { Component } from 'react'
import UserContext from './UserContext'
class HomePage extends Component {
static contextType = UserContext
render() {
const { user, setUser } = this.context
return (
<div>
<button
onClick={() => {
const newUser = { name: 'Irene', loggedIn: true }
setUser(newUser)
}}
>
Update User
</button>
<p>{`Current User: ${user.name}`}</p>
</div>
)
}
}
</code></pre>
<p>multiple static contextTypes in one component cannot be used. This leads to the necessity of having one really big Context for all global state in an application, so it's not sufficient for a large application. The method of creating a wrapper for Context is also difficult to test.</p>
<p>👉 Use const ___Context = React.createContext() to create context.</p>
<p>👉Pull **_Context.Provider and _**Context.Consumer out of ___Context</p>
<p>👉Wrap Provider around your parent component.</p>
<p>👉 A class can consume with static contextType = ___Context</p>
<p>👉A functional component can consume with const x = useContext(___Context)</p>]]></content:encoded>
</item>
<item>
<title><![CDATA[Usage of Pseudo-class selector :root ]]></title>
<link>http://irenaapp.de//blog-css-specificity-post/</link>
<guid>http://irenaapp.de//blog-css-specificity-post/</guid>
<pubDate>Mon, 03 Aug 2020 23:19:51 GMT</pubDate>
<description><![CDATA[The CSS :root pseudo-class selector is used to select the highest-level parent of a given specification. In the HTML specification, the…]]></description>
<content:encoded><![CDATA[<p>The CSS :root pseudo-class selector is used to select the highest-level parent of a given specification. In the HTML specification, the :root is essentially equivalent to the html selector.</p>
<p>In the CSS snippet below the :root and html styles will do the same thing:</p>
<pre><code class="language-css">:root {
background-color: gray;
}
html {
background-color: gray;
}
</code></pre>
<p>If you noticed I said :root is essentially equivalent to the html selector. In fact, the :root selector has more authority than html. This is because it’s actually considered a pseudo-class selector (like :first-child or :hover).</p>
<p>As a pseudo-class selector, it has more authority/higher specificity than tag selectors:</p>
<pre><code class="language-css">:root {
background-color: blue;
color: white;
}
html {
background-color: red;
color: white;
}
</code></pre>
<p>👉 Despite the <code>html</code> selector coming after, the :root selector still wins, thanks to its higher specificity!</p>
<p>Cross-Specification
In the HTML specification, the :root pseudo-class targets the highest-level parent: html.</p>
<p>Since CSS is also designed for SVG and XML you can actually use :root and it will just correspond to a different element.</p>
<p>For example, in SVG the highest-level parent is the svg tag.</p>
<pre><code class="language-css">:root {
fill: gold;
}
svg {
fill: gold;
}
</code></pre>
<p>Similar to HTML, the <code>:root</code> and <code>svg</code> tags select the same element, however the <code>:root</code> selector will have higher specificity.</p>
<p>👉 <strong>Uses</strong></p>
<p>What are the uses for <code>:root</code>? It’s a safe substitute for the <code>html</code>selector.</p>
<p><strong>This means you can do anything you’d normally do with the <code>html</code> selector:</strong></p>
<pre><code class="language-css">:root {
margin: 0;
padding: 0;
color: #0000ff;
font-family: 'Helvetica', 'Arial', sans-serif;
line-height: 1.5;
}
</code></pre>
<p>If you’d like, you can refactor this code to use CSS Custom Properties to create variables at the global level!</p>
<pre><code class="language-css">:root {
margin: 0;
padding: 0;
--primary-color: #0000ff;
--body-fonts: 'Helvetica', 'Arial', sans-serif;
--line-height: 1.5;
}
p {
color: var(--primary-color);
font-family: var(--body-fonts);
line-height: var(--line-height);
}
</code></pre>
<p>The added benefit of using :root instead of html is that you can style your SVG graphics! 🤯</p>
<pre><code class="language-css">:root {
margin: 0;
padding: 0;
--primary-color: #0000ff;
--body-fonts: 'Helvetica', 'Arial', sans-serif;
--line-height: 1.5;
}
svg {
font-family: var(--body-fonts);
}
svg circle {
fill: var(--primary-color);
}
</code></pre>]]></content:encoded>
</item>
<item>
<title><![CDATA[FlexBox Model]]></title>
<link>http://irenaapp.de//blog-css-flexbox-post/</link>
<guid>http://irenaapp.de//blog-css-flexbox-post/</guid>
<pubDate>Mon, 03 Aug 2020 23:19:51 GMT</pubDate>
<description><![CDATA[The Flexbox Model still contains the major elements of the Box Model (margin, padding, border and content), but offers flexibility to best…]]></description>
<content:encoded><![CDATA[<p>The Flexbox Model still contains the major elements of the Box Model (margin, padding, border and content), but offers flexibility to best fill the space with the container’s/parent’s children.</p>
<p>This tutorial will help you to understand the flexbox module a bit better so you can start to make your sites more responsive.</p>
<p>The following is starter code for a basic flexbox model demonstration – please follow along as we talk about flexbox!</p>
<pre><code class="language-css"><!DOCTYPE html>
<head>
<title>Flexbox</title>
<style>
* {
box-sizing: border-box;
font-family: 'Roboto'
}
.parent-container {
height: 700px;
background: green;
width: 700px;
padding: 20px;
}
.child-item {
height: 200px;
width: 200px;
margin: 0px;
padding: 20px;
}
.child-item:first-child {
background: orange;
}
.child-item.one {
background: purple;
}
.child-item.two {
background: aliceblue;
}
.child-item.three {
background: grey;
}
.child-item.four {
background: pink;
}
.child-item.five {
background: yellowgreen;
}
.child-item.six {
background: red;
}
.child-item.seven {
background: blanchedalmond;
}
.child-item.eight {
background: white;
}
.child-item.nine {
background: lightblue;
}
.child-item.nine {
background: darkred;
}
.child-item:last-child {
background: yellow;
}
</style>
</head>
<body>
<div class="parent-container">
<div class="child-item">Lisa Simpson</div>
<div class="child-item one">Bart Simpson</div>
<div class="child-item two">Maggie Simpson</div>
<div class="child-item three">Homer Simpson</div>
<div class="child-item four">Marge Simpson</div>
<div class="child-item five">Grampa Simpson</div>
<div class="child-item six">Santa's Little Helper</div>
<div class="child-item seven">Apu Nahasapeemapetilon</div>
<div class="child-item eight">Moe Szyslak</div>
<div class="child-item nine">Ned Flanders</div>
<div class="child-item ten">Snowball II</div>
</div>
<script src="" async defer></script>
</body>
</html>
</code></pre>
<h3>Parent Container (Flexbox) Properties</h3>
<p><strong>display: flex</strong>
The display property has several values we can use to position our containers on the screen. You may have seen block, inline-block, none, hidden, inline already, but the one we are going to focus on right now is called flex.</p>
<p>👉 First, what I would like you to do is envision a large container – a treasure chest, a toy box or a cardboard box – and then imagine putting items inside the container. The large container is what we call the parent or flexbox and the smaller items that go inside the container are the children or flex items.</p>
<p>When we add display:flex to a parent container, the property is assigned to that container and that container alone – the children do not inherit the property (however, they can use the property for their own containers that will affect their children).</p>
<p>This property opens all kinds of other properties we can use that we were not able to before: flex-direction, justify-content, align-items, align-self, flex-wrap and flex-flow.</p>
<p>Run the code editor above. Right now, you should see a large green container, the parent container, and 11 smaller containers, the child containers, inside the parent.</p>
<p>👉 The orientation of the child containers are on top of each other because the default is display: block. If you recall, when we use display: block, the container takes up the entire row it’s in. The margin’s default expands to the width of the parent container, resulting in both child containers being on top of each other.</p>
<p>👉 In contrast, using display: flex allows us to easily position the child containers any way we like in the parent container without having to use older box model properties like float and vertical-align.</p>
<p>🤖 Now try adding display: flex to the CSS in the style tag in the code editor so that <strong>the parent container’s CSS</strong> looks like this:</p>
<pre><code class="language-css">.parent-container {
height: 700px;
background: green;
width: 700px;
padding: 20px;
display: flex;
</code></pre>
<p>Adding <strong>display: flex</strong> to the <strong><code>.parent-container</code></strong> will result in a change to the orientation of the child containers. Once you hit , you should now see the <code>child containers</code> side-by-side.</p>
<p>By using <strong><code>display: flex</code></strong> instead of <strong><code>display: block</code></strong>, the default margin is <strong>set to 0.</strong> We can then manipulate it however we see fit!</p>
<p><strong>flex-direction</strong></p>
<p>🛑 The <strong>flex-direction property</strong> sets up the <strong>main axis of our container</strong>. The default setting in the flex container is row. When setting up the parent container with display:flex, there is no need to establish a flex-direction unless you need your content to be in a column.</p>
<p>👉 The <strong>main axis</strong> in the default direction is left to right and the cross axis is top to bottom, as seen here:</p>
<p><img src="../images/flex.png" alt="Cross Axis">
🛑 <strong>flex-direction: row establishes the main axis from left to right and the cross axis from top to bottom.</strong></p>
<p>Now add <strong>flex-direction:</strong> column to the <strong>.parent-container</strong> in code. What happens when you press?</p>
<p>👉 It seems to be that the axes flip when we switch flex-direction to column: what was our main axis becomes the cross axis and then what was our cross axis becomes the main axis, as illustrated below:</p>
<p><strong>flex-direction: row</strong> establishes the <strong>main axis</strong> from left to right and the <strong>cross axis from top to bottom</strong>.
Let’s try adding flex-direction: column to our .parent-container in the code editor above. What happens when you press?</p>
<p>It seems to be that the axes flip when we switch flex-direction to column: what was our main axis becomes the cross axis and then what was our cross axis becomes the main axis, as illustrated below:</p>
<p><img src="../images/axis.png" alt="Cross Axis"></p>
<p>🛑 <strong>flex-direction: column establishes the main axis from top to bottom and the cross axis from left to right.</strong>
As a result, our children containers in our example flipped their axes! So now the child containers are once again on top of each other.</p>
<p>🛑 The main to remember about <strong>flex-direction is that the direction of the main axis corresponds to the value of your flex-direction property (column is top to bottom, row is left to right).</strong></p>
<p><strong>Justify-content</strong> concerns itself with the spacing on the main axis and <strong>align-items</strong> concerns itself with spacing around the cross axis. We’ll get into those properties a little later.</p>
<p>👉 There are two other possibilities for <strong><code>flex-direction: row-reverse and column-reverse</code></strong>. These properties are very similar to <strong>row and column</strong>, but the <code>flex-items</code>are laid in a <strong>reverse order, right to left,</strong> in the case of <code>row-reverse</code>, and bottom to top for <code>column-reverse</code>.</p>
<p>The use case for these particular values comes when you need to have a different layout or order on your page from web to mobile or tablet.</p>
<p><strong>flex-wrap</strong></p>
<p>🛑So far we have learned how <strong>display: flex</strong> affects a parent’s child containers and then how to manipulate the flow of those child containers in a row or in a column. What if the size of the parent runs out of room? What happens? And how can we fix it?</p>
<p>👉 The answer comes in the form of the property called flex-wrap. By default, flex-wrap is set to nowrap. <strong>This means that the child containers can overflow the parent container, causing unwanted layout problems. Let’s try adding flex-wrap: wrap; to the .parent-container</strong> and see what happens in your code.</p>
<p><strong>flex-wrap: wrap</strong> makes sure that the contents of the main container don’t go outside that container’s border.
👉 The layout of the container will be much nicer. <strong>Flex-wrap</strong> will take all the children components, lay them side by side until it hits the width of the parent container and then move to the next row to add more child containers to repeat the process until all of the containers have been displayed.</p>
<p>🛑 <strong>Flex-wrap</strong> has three available properties: <strong>nowrap, wrap and wrap-reverse</strong>. wrap-reverse is the same as wrap except that it flows bottom to top instead of top to bottom.</p>
<p><strong>flex-flow</strong></p>
<p><strong>Flex-flow</strong> is shorthand for <strong>flex-direction and flex-wrap</strong>. The syntax is <strong>flex-flow: column wrap</strong> if you would like your flex-direction to be column and your flex-wrap to be wrap. <strong>flex-flow: row nowrap</strong> is the default value.</p>
<p><strong>justify-content</strong>
🛑 The justify content property is concerned with alignment along the main axis of the parent container. 👉 <strong>It helps to distribute your flex-items across the main axis without you having to calculate the space needed. The six most commonly used property values for justify-content are <code>flex-start (the default)</code>, <code>flex-end</code>, <code>center</code>, <code>space-around</code>, <code>space-between</code> and <code>space-evenly</code>.</strong></p>]]></content:encoded>
</item>
<item>
<title><![CDATA[Express 🤔 🛠]]></title>
<link>http://irenaapp.de//blog-express-post/</link>
<guid>http://irenaapp.de//blog-express-post/</guid>
<pubDate>Fri, 03 Jul 2020 23:19:51 GMT</pubDate>
<description><![CDATA[Overview and practice Express.js is the best choice when it comes to building web applications with Node.js. However, when saying web…]]></description>
<content:encoded><![CDATA[<h4>Overview and practice</h4>
<p><strong>Express.js</strong> is the best choice when it comes to building web applications with <strong>Node.js.</strong></p>
<p>However, when saying web applications with Node.js, it's often not for anything visible in the browser (excluding server-side rendering of a frontend application). Instead, Express.js, a web application framework for Node.js, enables you to build server applications in Node.js.</p>
<p>👉As a backend application, it is the glue between your frontend application and a potential database or other data sources (e.g. REST APIs, GraphQL APIs). Just to give you an idea, the following is a list of tech stacks to build client-server architectures:</p>
<p>👉 React.js (Frontend) + Express.js (Backend) + PostgreSQL (Database)</p>
<p>👉 Vue.js (Frontend) + Koa.js (Backend) + MongoDB (Database)</p>
<p>👉 Angular.js (Frontend) + Hapi.js (Backend) + Neo4j (Database)</p>
<h4>Express.js vs. Node.js</h4>
<p>There isn’t really any competition between Node.js and Express.js. In fact, the first thing to know about Express.js is that in a way Express.js is Node.js. Express.js is a framework that runs inside Node.js.</p>
<p>Node.js is a JavaScript runtime. <strong>It lets you run JavaScript code outside of your web browser.</strong> JavaScript is pretty useful, and you can do a lot of stuff with it. Being able to run JavaScript programs outside of a browser is especially useful when coding server-side backends for web programs in JavaScript. This is because most front end web programming is already written in JavaScript, so letting those programs communicate with a backend that’s also JavaScript makes for better functionality and speed.</p>
<h4>Express.js is Server side</h4>
<p>The only problem with Node.js is, that while it’s very useful for setting up servers, it wasn’t designed specifically for that application. That’s where Express.js comes in.
👉 Express.js is a framework designed to utilize Node.js specifically for running web servers. It takes out the effort of having to code complex server-side integrations for Node.js. It’s kind of like a <strong>server in a box for JavaScript</strong>; it helps you easily use templating solutions and organize your application’s routing with readable and well-organized code.</p>
<p>Express.js comes with a number of built-in features that work well in the server environment. These benefits include:</p>
<h5>👉 Faster server-side programming:</h5>
<p>Express.js takes a number of commonly used Node.js features and packages them into functions. These functions can be called anywhere in the program. This can save hundreds of lines of code by just calling these functions instead of having to write them.</p>
<p><strong>Routing:</strong> Node.js has a routing mechanism already, but it’s a little rudimentary.</p>
<p><strong>Express.js features are significantly more advanced and efficient routing mechanism that allows the web application to keep web page states through just their URLs.</strong></p>
<h5>Templating:</h5>
<p>👉 Express.js also features a <strong>templating engine</strong>. This lets the <strong>server-side build the webpage on its end, then send all of those values to the front end to display.</strong>
This allows for dynamic content and reduces the load on the client-side.</p>
<h4>Express.js Lives in the Stack</h4>
<p>Express.js is at its best when implemented in a stack (a stack is all of the code required to run a web application, from the front end user’s interaction all the way back to the backend processes that result from that click). Front end and back end development are usually split, for good reason. However, it usually means that different developers are working on different parts of a puzzle that, in the end, needs to fit together.</p>
<p><strong>Express.js functions powerfully as the second half to JavaScript front end applications, allowing users to create an entire stack that sticks to one language.</strong></p>
<p>👉 This is incredibly efficient because when it’s time for the front end developers to connect with backend dev work, there are fewer integration issues. It stands to reason that things will (usually) work out smoother if it’s all coded in the same language.</p>
<h3>Let's put hands on Practice</h3>
<h3>Installation</h3>
<p>Express is very simple to install. Simply install it via npm as you would with any other package.</p>
<pre><code class="language-bash">$ npm install express --save
</code></pre>
<h4>Usage</h4>
<p>Now that Express is installed, here’s what the most basic server looks like:</p>
<pre><code class="language-js">const express = require('express')
const app = express()
app.get('/', (req, res) => {
res.send('Beginners approaches!')
})
app.listen(3000, () => console.log('Beginners app listening on port 3000!'))
</code></pre>
<p>Now, run this script, and navigate to <code>localhost:3000</code> in your browser. You should see the message A Beginners approaches! in your browser window!</p>
<h5>What exactly does it mean? 🤔</h5>
<p>Let’s go over each section of this code to explain how Express works.</p>
<pre><code class="language-js">const express = require('express')
const app = express()
</code></pre>
<p>👉 The first line here is grabbing the main Express module from the package you installed.</p>
<p>👉 This module is a function, which we then run on the second line to create our app variable.</p>
<p>You can create multiple apps this way, each with their own <strong>requests and responses.</strong></p>
<pre><code class="language-js">app.get('/', (req, res) => {
res.send('A Beginners approaches!')
})
</code></pre>
<p>Actually, this bite of code is where we tell <strong>Express server how to handle a GET request to our server.</strong> Express includes similar functions for <code>POST</code>, <code>PUT</code>, etc. using <code>app.post(...)</code>, <code>app.put(...)</code>, and so on.</p>
<p>These functions take two main parameters. The first is the <strong>URL</strong> for this function to act upon. In this case, we are targeting <code>'/'</code>, which is the root of our website: in this case, <code>localhost:3000</code>.</p>
<p>The second parameter is a <strong>function with two arguments</strong>: <code>req</code>, and <code>res</code>.</p>
<p>👉 <code>req</code> represents the request that was sent to the server; We can use this object to read data about what the client is requesting to do.</p>
<p>👉 <code>res</code> represents the response that we will send back to the client. Here, we are calling a function on res to send back a response: 'An alligator approaches!'.</p>
<pre><code class="language-js">app.listen(3000, () => console.log('Beginners app listening on port 3000!'))
</code></pre>
<p>Finally, once we’ve set up our requests, we must start our server! We are passing 3000 into the listen function, which tells the app which port to listen on. The function passed-in as the second parameter is optional, and runs when the server starts up. This just gives us some feedback in the console to know that our application is running.</p>
<p>And there we have it, a basic web server! However, we definitely want to send more than just a single line of text back to the client.</p>
<h3>Middleware</h3>
<h4>What middleware is and how to set this server up as a static file server! 🤔</h4>
<p>With Express, we can write and use <strong>middleware functions</strong>, which have access to <strong>ALL http requests coming to the server</strong>. Which are:</p>
<p>👉 Execute any code.</p>
<p>👉 Make changes to the request and the response objects.</p>
<p>👉 End the request-response cycle.</p>
<p>👉 Call the next middleware function in the stack.</p>
<p>We can write our own middleware functions, or use third-party middleware by importing them the same way we would with any other package. Let’s start by writing our own middleware, then we’ll try using some existing middleware to serve static files.</p>
<p>🛑 To define a middleware function, we call <code>app.use()</code> and pass it a function.</p>
<p>Here’s a basic middleware function to print the current time in the console during every request:</p>
<pre><code class="language-js">app.use((req, res, next) => {
console.log('Time: ', Date.now())
next()
})
</code></pre>
<p>The <code>next()</code> call tells the middleware to go to the <strong>next middleware function</strong>, if there is one. 👉 ❗️This is important to <strong>include at the end of our function</strong> - otherwise, the r<strong>equest</strong> will get stuck on this middleware.</p>
<p>We can optionally pass a path to the middleware, which will only handle requests to that route. For example:</p>
<p>By passing <code>'/nest'</code> as the first argument to <code>app.use()</code>, this function will only run for requests sent to localhost:3000/nest.</p>
<p>Now, let’s try using existing middleware to serve static files. Express comes with a <strong>built-in middleware function:</strong> <code>express.static</code>. We will also use a third-party middleware function, <code>serve-index</code>, to display an <code>index</code> listing of the files.</p>
<p>First, inside the same folder where the express server is located, create a folder called public and put some files in there (any files will do, perhaps some images/avatars ).</p>
<p>Then, install the package <code>serve-index</code>:</p>
<pre><code class="language-bash">\$ npm install serve-index --save
</code></pre>
<p>Import the <code>serve-index</code> package at the top of the server file:</p>
<pre><code class="language-js">const serveIndex = require('serve-index')
</code></pre>
<p>Now, let’s include the <code>express.static</code> and s<code>erveIndex</code> middlewares and tell them the path to access from and the name of our folder:</p>
<pre><code class="language-js">app.use('/beginners', express.static('public'))
app.use('/beginners', serveIndex('public'))
</code></pre>
<p>Now, restart your server and navigate to localhost:3000/beginners. You should see a listing of all your files!</p>]]></content:encoded>
</item>
<item>
<title><![CDATA[GitHub]]></title>
<link>http://irenaapp.de//blog-github-post/</link>
<guid>http://irenaapp.de//blog-github-post/</guid>
<pubDate>Sat, 13 Jun 2020 23:13:10 GMT</pubDate>
<description><![CDATA[What is GitHub ? 🤔 GitHub is a code-hosting platform. It lets you and others work together on projects from anywhere. 👉 Before anything…]]></description>
<content:encoded><![CDATA[<h2>What is GitHub ? 🤔</h2>
<p><strong>GitHub is a code-hosting platform.</strong> It lets you and others work together on projects from anywhere.</p>
<p>👉 Before anything else, if you haven’t done it yet, you should go now to <strong>github.com</strong> and create an account.</p>
<blockquote>
<p>👉 GitHub is NOT Git. Git is a version control software that sets repositories. GitHub repository
hosting platform that understands Git. Git runs on your local machine, whereas GitHub runs on
the
Internet. Keep in mind some people consider GitHub as a Social Network to share code.</p>
</blockquote>
<h3>Clone a GitHub repository</h3>
<p>To <strong>clone</strong> a GitHub repository is to copy the entire project to your local computer. Basically, it is a combination of:</p>
<p>👉 <strong>git init</strong> (create the local repository)</p>
<p>👉 <strong>git remote</strong> add (add the URL to that repository)</p>
<p>👉 <strong>git fetch</strong> (fetch all branches from that URL to your local repository)</p>
<p>👉 <strong>git checkout</strong> (create all the files of the main branch in your working tree)</p>
<p>For now, forget about the <strong>fetching</strong> and the <strong>checkout</strong>.
We will learn about branches in another lesson.</p>
<p>But you should know that <code>git clone</code> already <strong>initializes your local repository and adds the URL of the remote repository so the system knows where to put the changes and from where get the changes while you work.</strong></p>
<pre><code class="language-bash">
$ git clone
</code></pre>]]></content:encoded>
</item>
<item>
<title><![CDATA[What is recursion ]]></title>
<link>http://irenaapp.de//blog-what-is-recursion-in-js/</link>
<guid>http://irenaapp.de//blog-what-is-recursion-in-js/</guid>
<pubDate>Sat, 11 Apr 2020 23:14:21 GMT</pubDate>
<description><![CDATA[What is recursion? Recursion is a process of calling itself. A function that calls itself is called a recursive function. The syntax for…]]></description>
<content:encoded><![CDATA[<h2>What is recursion?</h2>
<blockquote>
<p>Recursion is a process of calling itself. A function that calls itself is called a recursive function.</p>
</blockquote>
<p>The syntax for recursive function is:</p>
<pre><code class="language-js">function recurse() {
// function code
recurse();
// function code
}
recurse();
</code></pre>
<p>👉 The <code>recurse()</code> function is a recursive function. <strong>It is calling itself inside the function.</strong></p>
<p>A recursive function must have a condition to stop calling itself. Otherwise, the function is called indefinitely.</p>
<p>Once the condition is met, the function stops calling itself. This is called a base condition.</p>
<p>To prevent infinite recursion, you can use if...else statement (or similar approach) where one branch makes the recursive call, and the other doesn't.</p>
<pre><code class="language-js">function recurse() {
if(condition) {
recurse();
}
else {
// stop calling recurse()
}
}
recurse();
</code></pre>
<p>Print Numbers</p>
<pre><code class="language-js">// program to count down numbers to 1
function countDown(number) {
// display the number
console.log(number);
// decrease the number value
const newNumber = number - 1;
// base case
if (newNumber > 0) {
countDown(newNumber);
}
}
countDown(4);
</code></pre>
<p>👉 the user passes a number as an argument when calling a function.</p>
<p>In each iteration, the number value is decreased by 1 and function <code>countDown()</code> is called until the number is positive. Here, <code>newNumber > 0 </code>is the base condition.</p>
<p>This recursive call can be explained in the following steps:</p>
<pre><code class="language-bash">countDown(4) prints 4 and calls countDown(3)
countDown(3) prints 3 and calls countDown(2)
countDown(2) prints 2 and calls countDown(1)
countDown(1) prints 1 and calls countDown(0)
</code></pre>
<p>When the number reaches 0, the base condition is met, and the function is not called anymore.</p>
<p>Find Factorial</p>
<pre><code class="language-js">// program to find the factorial of a number
function factorial(x) {
// if number is 0
if (x === 0) {
return 1;
}
// if number is positive
else {
return x * factorial(x - 1);
}
}
const num = 3;
// calling factorial() if num is non-negative
if (num > 0) {
let result = factorial(num);
console.log(`The factorial of ${num} is ${result}`);
}
// The factorial of 3 is 6
</code></pre>
<p>When you call function factorial() with a positive integer, it will recursively call itself by decreasing the number.</p>
<p>This process continues until the number becomes 1. Then when the number reaches 0, 1 is returned.</p>
<pre><code class="language-JS">factorial(3) returns 3 * factorial(2)
factorial(2) returns 3 * 2 * factorial(1)
factorial(1) returns 3 * 2 * 1 * factorial(0)
factorial(0) returns 3 * 2 * 1 * 1
</code></pre>]]></content:encoded>
</item>
<item>
<title><![CDATA[Git-Version Control System]]></title>
<link>http://irenaapp.de//blog-git-t-post/</link>
<guid>http://irenaapp.de//blog-git-t-post/</guid>
<pubDate>Sun, 15 Sep 2019 23:14:21 GMT</pubDate>
<description><![CDATA[Git is not GitHub. Git is the system, and GitHub is a repository hosting service (the most popular of many). 👉 After this lesson you will…]]></description>
<content:encoded><![CDATA[<p>Git is not GitHub. Git is the system, and GitHub is a repository hosting service (the most popular of many).</p>
<p>👉 After this lesson you will be able to:</p>
<ul>
<li>Understand what a version control system is</li>
<li>Understand the advantages of using Git</li>
<li>Create a new repository</li>
<li>Clone a repository</li>
<li>Check the status of a repository</li>
<li>Add files to a commit</li>
<li>Commit files</li>
<li>Push files into a remote repository</li>
<li>See and understand the git log</li>
<li>Create an account in GitHub</li>
<li>GitHub create account, create repo, clone repo, add files, commit files, push files, git log</li>
</ul>
<h3>Goals</h3>
<p>Create a local project and launch it to a live server with Git using the command line.</p>
<h3>What is Git?</h3>
<p><strong>Git</strong> is a difficult subject to tackle for self-taught web developers who didn't learn to code with a team. If you've always worked alone and want an explanation of how to get started with Git, this tutorial is for you.</p>
<p>Web development projects usually require the effort of more than one programmer. During web applications life cycle a lot of changes occurs: new features, bugs management, re-factorization of the code. The result?</p>
<p>New releases, code that has to be organized and accesible for everyone while we track changes and a easy and practical way of putting new code together without breaking what is already there.</p>
<p>Git is a free and open source distributed version control system. This means Git can do all of the tasks needed above.</p>
<p>A version control system is software that helps developers to track changes and distribute their code.</p>
<h3>Git advantages</h3>
<h4>👉 Distributed architecture</h4>
<p>Git is an example of a DVCS (Distributed Version Control System). This means that rather than have one single place for the full version history of the software, every developer gets to have his own working copy of the code and this copy is also a repository with the full history of all changes ever done to that version of the code.
👉 It is used to keep track of revisions and allow a developer or dev team to work together on a project through branches.</p>
<h4>👉 Flexibility</h4>
<p>Git allows us to have various development workflows, so it adapts to any project size. It also provides compatibility with a lot of existing systems and protocols.</p>
<h4>👉 Everyone knows Git</h4>
<p>Git has the functionality, performance, security and flexibility that most teams and individual developers need, that’s why everyone uses it. Also, a lot of developers already have Git experience, so it is a de facto standard.</p>
<h4>👉 Git is open source</h4>
<p>Git is an open source project with more than ten years of evolution. The project maintainers have shown balanced judgment and a mature approach to meeting the long term needs of its users with regular releases that improve usability and functionality.</p>
<p>This also means Git community is huge and a lot of good quality documentation is available on the Internet, through books, tutorials and dedicated websites.</p>
<h3>Creating a Repository</h3>
<p><strong>Git</strong> manages different projects with different repositories. We generally call them <strong>repos</strong> for short 🤔</p>
<p>To create a new repo in your project, open your terminal and go to your project folder. Right in this folder, at the top of your project, type:</p>
<pre><code class="language-bash">
$ git init
Initialized empty Git repository in [your .git directory path]
</code></pre>
<blockquote>
<p>❗️💡 You don’t need to type the <code>$</code> symbol. It is provided by your terminal to let you know
where you should type your commands.</p>
</blockquote>
<p>🛑 👉 This command creates a <strong>hidden directory</strong> <code>.git</code> in that folder. This hidden directory is where <strong>Git operates and stores it’s data</strong>, so right now, it has an empty repository in it.</p>
<p>👉 Type <code>ls -la</code>in your terminal to see the new folder.</p>
<p>Checking the Status
Next up, let’s type the git status command to see what the current state of our project is:</p>
<pre><code class="language-bash">$ git status
# On branch master
#
# Initial commit
#
nothing to commit (create/copy files and use "git add" to track)
</code></pre>
<blockquote>
<p>🛑 💡</p>
<p>It’s healthy to run git status often. Sometimes things change and you don’t notice it.</p>
</blockquote>
<h3>Adding and committing changes</h3>
<p>Create a file called <strong>index.html</strong></p>
<pre><code class="language-bash">$ touch index.html
Run the git status command again to see how the repository status has changed:
$ git status
On branch master
Initial commit
Untracked files:
(use "git add <file>..." to include in what will be committed)
index.html
nothing added to commit but untracked files present (use "git add" to track)
</code></pre>
<p>🛑
As you can see, <strong>Git is now detecting changes</strong> -in this case, a <strong>new file.</strong></p>
<p>🛑 Also, it detects that this new file is not being tracked and Git suggests how to add this file in the next commit.</p>
<p>👉 A <strong>Git commit</strong> works a lot like taking a picture. It takes a snapshot of the files added to the commit.</p>
<p>This is a very important concept to understand. Imagine it’s your sibling’s birthday and you are the unofficial photographer. You get to choose which family members are going to be included in each picture. You select some of them, ask them to stay still somewhere in the house and then you take a picture. With Git, family members are your project files, when you ask them to stay in a certain place you’re adding and when you take the picture you’re committing the changes.</p>
<h3>⚠️ 🛑</h3>
<blockquote>
<p>You are not making copies of the files you’re tracking. You are just creating a
snapshot of the files you added.</p>
</blockquote>
<h3>Adding the file</h3>
<p>Now, let’s add <code>index.html</code> to the tracked group.</p>
<pre><code class="language-bash">$ git add index.html
$ git status
On branch master
Initial commit
Changes to be committed:
(use "git rm --cached <file>..." to unstage)
new file: index.html
</code></pre>
<p>If you need to add every file in your filesystem, you can type:</p>
<pre><code class="language-bash">$ git add .
</code></pre>
<p>👉 As you can see in your <strong>Git status output</strong>, you can now also remove the file from the tracking group. This is known as <strong>unstage</strong> the changes (to add them is to stage the changes to the commit).</p>
<h3>🛑 Committing the files</h3>
<p>To commit your changes simply type</p>
<pre><code class="language-bash">
\$ git commit -m "Add the index.html file"
[master (root-commit) d100e63] Add the index.html file
1 file changed, 0 insertions(+), 0 deletions(-)
create mode 100644 index.html
</code></pre>
<p>You could type <code>git status</code> again to check your repository status now.</p>
<h3>Git log</h3>
<p>So we’ve made a commit. But if we have several commits, we would like to be able to see the history of changes we’ve done. Think of Git’s log as a journal that remembers all the changes we’ve committed so far, in the order we committed them. Try running it now:</p>
<pre><code class="language-bash">$ git log
</code></pre>
<p>The output will be an opened txt file something like this</p>
<pre><code class="language-bash">commit d100e63a4266ccaf1c0fe0e0c8e65b40440e4327
Author: irenedoe <irie6@gmail.com>
Date: Sat June 20 11:42:22 2019 +0200
Add the index.html file
</code></pre>
<p>The log file will open in your terminal with the <a href="https://en.wikipedia.org/wiki/Less_(Unix)">less</a> program and to exit simply type <code>q</code>.</p>
<h3>Remote repositories</h3>
<p>To collaborate on any <strong>Git project</strong>, you need to know <strong>how to manage your remote repositories.</strong></p>
<p>Remote repositories are versions of your project that are hosted on the Internet or network somewhere. Collaborating with others involves managing these remote repositories and pushing and pulling data to and from them when you need to share work.</p>
<p><img src="https://i.imgur.com/iDbve7w.png" alt=""></p>
<h3>👉 Resources</h3>
<ol>
<li>
<p><a href="https://try.github.io/"> Learn Git</a></p>
</li>
<li>
<p><a href="https://education.github.com/git-cheat-sheet-education.pdf">Git Cheatsheet</a></p>
</li>
</ol>
<h4>Happy Coding Journey ! 🤓 🌴</h4>]]></content:encoded>
</item>
<item>
<title><![CDATA[Functional & Class in React]]></title>
<link>http://irenaapp.de//blog-react-post/</link>
<guid>http://irenaapp.de//blog-react-post/</guid>
<pubDate>Sun, 15 Sep 2019 23:14:21 GMT</pubDate>
<description><![CDATA[Functional & class components in React 🤔 🤓 React is a framework that allows us to encapsulate code so to make it more reusable. These…]]></description>
<content:encoded><![CDATA[<h3>Functional & class components in React 🤔 🤓</h3>
<p>React is a framework that allows us to encapsulate code so to make it more reusable. These encapsulated code snippets are called components. They can hold their own logic and state without interfering with what’s going on in the Document Object Model (DOM).</p>
<p>Splitting the website into smaller bite-size components to pass data around allows the code to become reusable and more DRY (Don’t Repeat Yourself). There are two main types of components that you will encounter in React are Functional and Class Components.</p>
<p>At a very high level, React components are basically JavaScript functions that accept props as a parameter and return some React elements that basically describe what should be on the screen:</p>
<p>🛑</p>
<pre><code class="language-js">import React from 'react'
import ReactDOM from 'react-dom'
const Greeting = (props) => {
return <div>Hello, {props.name}</div>
}
const element = <Greeting name="Irene" />
ReactDOM.render(element, document.getElementById('root'))
</code></pre>
<p>The React element in this case here is a <code><div></code> with some text in it. That text uses a props object that has been passed into the component. That props object will pass data down to children components from their parents.</p>
<p>In this instance, the prop that has been passed down is name. Element represents the parent.</p>
<p>Any property you pass into the <code><Greeting /></code>component will make it to the props object and be available to use inside Greeting. This makes Greeting super reusable since we can pass in any name we would like into the component.</p>
<h3>Functional Components 🤔</h3>
<p><strong>Functional components,</strong> are basically JavaScript functions. You can use EcmaScript 5 (ES5) or EcmaScript a6 (ES6) syntax when creating React components.</p>
<p>👉 As a rule, React components must be <strong>Capitalized to indicate they are indeed components.</strong></p>
<pre><code class="language-html"><!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Basic React Component</title>
</head>
<body>
<!-- App is inserted at thr root node -->
<div id="root"></div>
<!-- React CDN -->
<script
src="https://unpkg.com/react@16/umd/react.development.js"
crossorigin
></script>
<!-- React-DOM CDN -->
<script
src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"
crossorigin
></script>
<!-- React Components can be rendered here -->
<script async>
'use strict'
const element = React.createElement
function Greeting() {
return element('h4', null, `Hello, World!`)
}
function App() {
return element(Greeting)
}
const domContainer = document.querySelector('#root')
ReactDOM.render(element(App), domContainer)
</script>
</body>
</html>
</code></pre>
<p>The code snippet above is an example of how an ES5 functional component looks like when we are not using JSX, but plain vanilla JavaScript. Don’t worry too much about what’s going on in the HTML. Focus on the JavaScript logic: we have an element that’s being created, a function that’s returning something and then that function is being rendered to some sort of ReactDOM.</p>
<p>What JSX – short for JavaScript <strong>XML Extension</strong> – basically allows us to do is to write HTML in our JavaScript to make it more akin to what we are used to seeing in HTML. In the code example above, we are purely using JavaScript to create our HTML element and then using React’s createElement method to insert an <code><h4></code>into the DOM at the <code><div id=”root />.</code></p>
<p>If we were to scale our application – make our application much bigger than it is – this type of writing would become cumbersome fairly quickly. JSX was created basically as syntactic sugar for the React.createElement method and allows us to scale our apps much quicker.</p>
<p>Here is an example bellow of how both an ES5 and an ES6 functional component looks like using JSX:</p>
<p>ES5 Functional Component</p>
<pre><code class="language-js">import React from 'react'
import ReactDOM from 'react-dom'
function Animal(props) {
const element = <h1>My dogs name is {props.name}</h1>
return element
}
function App() {
return <Animal name="Blackflash" />
}
const domContainer = document.querySelector('#root')
ReactDOM.render(<App />, domContainer)
</code></pre>
<p>ES6 Functional Component</p>
<pre><code class="language-js">const Animal = (props) => {
const element = <h1>My dog name is {props.name}</h1>
return element
}
const App = () => {
return <Animal name="Blackflash" />
}
const domContainer = document.querySelector('#root')
ReactDOM.render(<App />, domContainer)
</code></pre>
<p>Functional components were known as stateless components. This means that the main purpose of the component was to be presentational – to look good on the page. Quite often, data was passed to these functional components so that they could display something on the user interface.</p>
<p>With the advent of React v.16 that all changed. We will get into that in a little bit. For right now, just know that functional components exist to receive some sort of data from a parent or from some global object to present something to the client.</p>
<h3>Class Components 🤔</h3>
<p>Class components are a little more complicated than “just” a JavaScript function. Class components in React borrow the concept of the ES6 JavaScript class. The structure of a class in JavaScript is pretty much an object that has attributes and methods associated with it. We use the <code>this</code> keyword to access an instance of that object and interact with it.</p>
<p>In React, for the most part, the structure is the same. React class components are an instance of an object and this object has what we call state. At a high level, state is just data that the component holds – think of it just as another way to set up attributes and bind it to the class. As a developer you can then do whatever you would like with that data: present it on screen, pass it around to other components, use it to do other logic, etc.</p>
<p>An ES6 class component is always capitalized, just like with functional components – that is a React rule so that the <strong>transpiler</strong> knows it’s a component. Because we are inheriting the component structure from React itself, we have to extend React’s <strong>Component class</strong>. Inside that block of code is where we will put our state:</p>
<pre><code class="language-js">import React from 'react'
import ReactDOM from 'react-dom'
import Name from './Name'
// the 'this' keyword needs to be used when we are talking about an instance of a class. So it will go in front of the methods and state when referring to it in the render method.
class Animal extends React.Component {
constructor(props) {
super(props)
this.state = {
species: [
'wolf',
'leopard',
'elephant',
'monkey',
'dolphin',
'horse',
'dog',
'squirrel',
],
}
}
render() {
return (
<div>
{this.state.species.map((animal) => {
return <Name animal={animal} />
})}
</div>
)
}
}
ReactDOM.render(<Animal />, document.getElementById('root'))
</code></pre>
<p>🛑 <strong>State</strong> is an <strong>object full of properties and values.</strong> The state in the snippet has a <strong>property of species and its value is an array full of animals.</strong> To refer to or interact with this array at all, we use <code>this.state.species</code>.</p>
<p>The purpose of the class component above is to pass the name of the animal down to the <code><Name /></code> component. The <code><Name /></code>component’s job is to do something with that data when it gets it.</p>
<p>👉 <strong>The Animal’s state will become part of a props object when it is passed to a functional or other class component. It will be able to be accessed in child components as long as it keeps getting passed down.</strong></p>
<p>🛑 <strong>Remember</strong>:</p>
<p>👉 ⚠️ <strong>In React, data flows down from parent component to child component only one level. You must pass it down another level if you need the data in the parent’s grandchild component.</strong></p>
<p>Another feature of class components in React is that we have access to and use <strong>lifecycle methods to keep track of the state.</strong></p>
<p>🛑 React lifecycles typically have three phases:</p>
<p>👉 They are <strong>created (Mounting)</strong>, they <strong>live (Update)</strong> and they <strong>die (Unmounting)</strong>.</p>
<p>There are methods to access and/or change state at each of the stages of the lifecycle method:</p>
<p>👉 <strong>ComponentDidMount()</strong> – this is the lifecycle method where we would make AJAX requests/network requests to initialize state. Use this.setState() to load your retrieved data into state.
ComponentDidUpdate() – any updates to state occur here after a user has interacted with the application.</p>
<p>👉 <strong>ComponentDidUnmount()</strong> – this is a cleanup function that occurs when the component unmounts. It’ll take care of timers, AJAX requests, etc.
There are more lifecycle methods than these – those listed are just the main ones. Please see React documentation for more information about these methods.</p>
<p>👉 Finally, in contrast to the functional component’s <strong>return</strong> statement, <strong>class components</strong> use a <strong><code>render() method</code></strong>. This method is <strong>invoked after <code>ReactDOM.render()</code> passes</strong> the Animal component and <strong>React calls its constructor</strong>.</p>
<p>👉 <strong>State is then initialized and then the render method is called to actually put content on the screen.</strong></p>
<p>remember that functional components prior to React v. 16 were primarily presentational – they didn’t handle state – they just displayed it. Class components detailed all the state logic for us and passed the information down to other components as props.</p>
<h3>Functional Components and useState()</h3>
<p>In 2018, React introduced the idea of <strong>React Hooks</strong>. Hooks are a clean and concise way of utilizing lifecycle methods and state inside a Functional Component.</p>
<p>Most everything is very similar to everything we have covered so far. We have some state, we need to do stuff with it, and we need to pass it somewhere else. The main objectives are the same. The syntax is much cleaner – it just requires a little bit of getting used to.</p>
<p>❗️ My advice is to practice, and get some repetitions for class components, really understand how the <strong>data flow works in React.</strong></p>
<p>Let’s start out with the code that we had before:</p>
<pre><code class="language-js">import React from 'react'
import ReactDOM from 'react-dom'
const Animal = (props) => {
const element = <h1>My dogs name is {props.name}</h1>
return element
}
const App = () => {
const [state, setState] = useState('Blackflash')
return <Animal name={state} />
}
const domContainer = document.querySelector('#root')
ReactDOM.render(<App />, domContainer)
</code></pre>
<p>We have two components, one <code>Animal</code> and one <code>App</code>. It looks like App is returning Animal and passing in a prop called name with a value of “Blackflash”.</p>
<p>Believe it or not, there isn’t much we have to do to convert this into some stateful logic. Let’s take a look at the <code><App></code> component. We’re are going to follow these steps:</p>
<pre><code class="language-js">import React, { useState } from 'react'
</code></pre>
<p>👉 this line will import the hook, <code>useState</code>.</p>
<pre><code class="language-js">const [state, setState] = useState('Blackflash')
</code></pre>
<p>👉 this line initializes our <strong>state</strong>. State and <code>setState</code> here are arbitrary words. You can name these whatever you’d like. It’s customary to name them after what the <strong>value</strong> is.</p>
<p>👉 <strong>state is the actual state</strong>. The <strong>initial state is inside the parentheses</strong> in <code>useState()</code>.</p>
<p>👉 <code>setState</code> is similar to <strong><code>this.setState()</code></strong>.</p>
<p>ℹ️ ❗️This is the method that will change the state as you journey through your application.</p>
<pre><code class="language-js">return <Animal name={state} />
</code></pre>
<p>👉 Replace “Blackflash” with <code>{state}</code>. When writing JavaScript in <strong>JSX</strong>, use curly braces.</p>
<p>👉 <strong>Curly braces allows to pass in the variable.</strong></p>
<p>One of the features that defined class components, the <strong>React Lifecycle</strong>, with its various methods, is skimmed down to <strong>one basic hook that encapsulates all the methods.</strong></p>
<p>🛑 <code>The useEffect()</code> <strong>hook can mount, update and unmount the React component it’s in.</strong></p>
<h3>Let's Sum Up:</h3>
<p>In React v. 16, <strong>functional components were purely used as a presentational view layer with no use of state except as props that were passed down from class components.</strong></p>
<ul>
<li>Class components held all of the state of the application and passed the data around.</li>
<li>Class components utilized life cycle methods that mounted, updated and unmounted our React component.</li>
<li>And about also React Hooks, a new pattern released by React in version 16, allows for functional components to be stateful and have it’s own version of lifecycle methods.</li>
</ul>]]></content:encoded>
</item>
<item>
<title><![CDATA[Arrow Functions in JavaScript]]></title>
<link>http://irenaapp.de//blog-javascript-functions-post/</link>
<guid>http://irenaapp.de//blog-javascript-functions-post/</guid>
<pubDate>Sun, 15 Sep 2019 23:14:21 GMT</pubDate>
<description><![CDATA[Arrow functions (also called “fat arrow functions”) are undoubtedly one of the more popular features of ES6. They introduced a new way of…]]></description>
<content:encoded><![CDATA[<p>Arrow functions (also called “fat arrow functions”) are undoubtedly one of the more popular features of ES6. They introduced a new way of writing concise functions.</p>
<p>ES5</p>
<pre><code class="language-js">function timesTwo(params) {
return params * 2
}
function timesTwo(params) {
return params * 2
}
timesTwo(4) // 8
</code></pre>
<pre><code class="language-js">var timesTwo = (params) => params * 2
timesTwo(4) // 8
</code></pre>
<h3>Introduction</h3>
<p><strong>Arrow functions</strong> are a new way to write anonymous function expressions, and are similar to lambda functions in some other programming languages, such as Python.</p>
<p><strong>Arrow functions</strong> differ from traditional functions in a number of ways, including the way their scope is determined and how their syntax is expressed. Because of this, arrow functions are particularly useful when passing a function as a parameter to a higher-order function, such as when you are looping over an array with built-in iterator methods. Their syntactic abbreviation can also allow you to improve the readability of your code.</p>
<p>In this article, you will review <strong>function declarations and expressions</strong>, learn about the differences between traditional function expressions and arrow function expressions, learn about lexical scope as it pertains to arrow functions, and explore some of the syntactic shorthand permitted with arrow functions.</p>
<h3>Defining Functions</h3>
<p>Before delving into the specifics of arrow function expressions, this tutorial will briefly review traditional JavaScript functions in order to better show the unique aspects of arrow functions later on.</p>
<p>The How To Define Functions in JavaScript tutorial earlier in this series introduced the concept of function declarations and function expressions. A function declaration is a named function written with the function keyword. Function declarations load into the execution context before any code runs. This is known as hoisting, meaning you can use the function before you declare it.</p>
<p>Here is an example of a sum function that returns the sum of two parameters:</p>
<pre><code class="language-js">function sum(a, b) {
return a + b
}
</code></pre>
<p>The usual way to define JavaScript functions is using the function declaration or function expression:</p>
<pre><code class="language-js">// Function declaration
function greet(who) {
return `Hello, ${who}!`
}
// Function expression
const greetExpression = function (who) {
return `Hello, ${who}!`
}
</code></pre>
<p>But functions can be further improved. Making the syntax shorter (useful for writing short callbacks) and ease the resolving of this created a new type of functions named arrow functions.</p>
<p>👉 The central symbol of an arrow function is the fat arrow =>. On the left side enumerate the parameters (param1, param2, ..., paramN) and on the right side write the body { ... }.</p>
<pre><code class="language-js">(param1, param2, ..., paramN) => { ... }
</code></pre>
<p>Let’s define an arrow function to greet a person:</p>
<pre><code class="language-js">const greet = (who) => {
return `Hello, ${who}!`
}
greet('Daniel Doe') // => 'Hello, Daniel Doe!'
</code></pre>
<p><strong>greet</strong> is an arrow function. The symbol => delimits the parameters in parentheses (who) and the function body consisting of return <code>Hello, ${who}!</code>.</p>
<p>greet('Daniel Doe') is how you call an arrow function. There’s no difference between calling a regular function and an arrow function.</p>]]></content:encoded>
</item>
<item>
<title><![CDATA[How to install and use Node - npm]]></title>
<link>http://irenaapp.de//blog-nodejs-post/</link>
<guid>http://irenaapp.de//blog-nodejs-post/</guid>
<pubDate>Sun, 15 Sep 2019 23:14:21 GMT</pubDate>
<description><![CDATA[Goals 👉Learn what Node.js and npm are; 👉 Set up Node.js and npm on Linux and Mac What is npm? npm doesn't stand for Node Package Manager…]]></description>
<content:encoded><![CDATA[<p><strong>Goals</strong></p>
<p>👉Learn what Node.js and npm are;</p>
<p>👉 Set up Node.js and npm on Linux and Mac</p>
<h3>What is npm?</h3>
<p>npm doesn't stand for Node Package Manager*, which means it’s the tool to connect to the repository containing all the Node.js programs, plugins, modules and so on.</p>
<p>*npm actually does not stand for "Node Package Manager" but essentially that's what it is and does, so most people refer to it that way.</p>
<h3>What is Node.js?</h3>
<p>JavaScript is a client-side programming language, which means it’s processed in the browser. With the advent of Node.js, JavaScript can also be used as a <strong>server-side language.</strong></p>
<h3>Local vs. Global</h3>
<p>This is the most confusing concept to understand at first, so it's important to let this settle in. Traditionally, you're used to globally installing any sort of program or software on your computer. If you want Spotify, you'll download Spotify, and then it will be available to you.</p>
<p>With <strong>npm</strong>, you will have some global installs, but mostly everything will be done on a local project basis, meaning you'll have to install everything you need for each project in its own directory. If you want to have a project running Gulp and Sass, you'll create a directory, with a new <strong><code>npm install</code></strong>.</p>
<p>For future reference, any global installations will have the <code>-g</code> flag.</p>
<h3>Installation on a Mac or Linux</h3>
<p>In order to install everything on a Mac, we'll be running commands in Terminal.app, and Linux distributions vary.</p>
<p>Install Node.js and npm
We’re going to use <strong>Node Version Manager (nvm)</strong> to install Node.js and <code>npm</code>.</p>
<pre><code class="language-js">
$ curl -o- https://raw.githubusercontent.com/creationix/nvm/v0.33.1/install.sh
| bash
</code></pre>
<p>Open the **<code>~/.bash_profile</code>**file, and make sure source ~/.bashrc is written in there somewhere. Restart the terminal.</p>
<p>Run the install command.</p>
<pre><code class="language-js">
nvm install node
</code></pre>
<h3>Creating your first app with Node.js</h3>
<p>In this lesson we’re going to create a real Node.js app from start to finish.
You will find out what "low level" means and we will have to manage all parts of the web server that will handle the visitor’s HTTP requests and give them an HTML webpage.</p>
<p>This will be a chance for you to experiment with the infamous callbacks, the functions that are run as soon as an event occurs. Node.js is full of them, so you won’t be able to avoid them! ;)</p>
<h3>Web servers and threads</h3>
<p>Node.js is low level. So low level that you will have to do things that you aren’t used to doing to make your program work properly.</p>
<p>When you create websites with PHP for example, you associate the language with an HTTP web server such as Apache or Nginx. Each of them has its own role in the process:</p>
<p>Apache manages HTTP requests to connect to the server. Its role is more or less to manage the in/out traffic.</p>
<p>PHP runs the <code>.php</code> file code and sends the result to Apache, which then sends it to the visitor.</p>
<p>As several visitors can request a page from the server at the same time, Apache is responsible for spreading them out and running different threads at the same time. Each thread uses a different processor on the server (or a processor core).</p>
<p>🛑 Node.js doesn’t use an HTTP server like Apache. In fact, it’s up to us to create the server!</p>
<h3>Constructing your HTTP server</h3>
<pre><code class="language-js">var http = require('http')
var server = http.createServer(function (req, res) {
res.writeHead(200)
res.end('Welcome on board everybody!')
})
server.listen(8080)
</code></pre>
<p>In some ways it’s the "minimal code" for a Node.js project. Put it in a file and name it server.js (for example).</p>
<p>👉 <strong>What does this code do?</strong></p>
<p>It creates a <strong>mini web server</strong> which sends a "Hi everybody" message in every case, regardless of the page requested. This server is launched on the 8080 port on the last line.</p>
<h3>Let’s analyze some code</h3>
<pre><code class="language-js">var http = require('http')
</code></pre>
<p><strong><code>require</code></strong> makes a <strong>call</strong> to a Node.js library, here it’s the <code>"http"</code> library which allows us to create a web server. There are loads of libraries like this one, most of them can be downloaded using NPM, Node.js’s packet manager (we’ll learn how to use that later on).</p>
<p>The <code>http</code> variable represents the JavaScript object that will let us launch a web server and that’s exactly what we’re doing here:</p>
<pre><code class="language-js">var server = http.createServer()
</code></pre>
<p>We call the <code>createSever()</code> function contained within the <code>http</code> object and we save this server in the server variable. You’ll notice that the <code>createServer</code> function takes on a setting and that this <strong>setting is a function</strong>. This is why the instruction is a little complicated, because it <strong>runs over multiple lines:</strong></p>
<pre><code class="language-js">var server = http.createServer(function (req, res) {
res.writeHead(200)
res.end('Welcome on board everybody!')
})
</code></pre>
<p>All this code corresponds to a call to the <strong><code>createServer()</code></strong>. Its settings contain the function to be run when a visitor connects to our website.</p>
<p>🛑 Note that you can do this in two steps, as mentioned previously. The function to be run is the <strong>callback</strong> function. We can define it beforehand in a variable and transmit this variable to <code>createServer()</code>. This way, the code is exactly the same as the previous one:</p>
<pre><code class="language-js">// Code exactly the same as the previous one
var instructionsNewVisitor = function (req, res) {
res.writeHead(200)
res.end('Hi everybody!')
}
var server = http.createServer(instructionsNewVisitor)
</code></pre>
<p>👉 It’s very important that you understand this idea, because Node.js only works like that. There are callback functions everywhere and, generally speaking, they are placed within the lines of another function as you saw in the first code. This can seem a little tough to read, but you will soon get the hang of it, don’t worry. 😄</p>
<p>🛑 Don’t forget to close the callback function properly with a brace, to close the brackets that contain the function, and to place the infamous semicolon. This is why you see the }); symbols on the last line of my first code.</p>
<p>👉 <strong>The callback function is therefore called each time a visitor connects to the website.</strong> It takes on 2 settings:</p>
<p>The visitor’s request (<code>req</code> in the examples): this <strong>object contains all the information about what the visitor asked for</strong>. In it you will find the name of the page that was requested, the settings, and any fields filled in on a form.</p>
<p>The response that you should send back (<code>res</code> in the examples): this is the object that you need to fill to give a response to the visitor. In the end, <code>res</code> will generally contain the <strong>HTML</strong> code of the page to be sent to the visitor.</p>
<p>Here, we are doing 2 simple things in the response:</p>
<pre><code class="language-js">res.writeHead(200)
res.end('Hi everybody!')
</code></pre>
<p>To be continued.....</p>]]></content:encoded>
</item>
<item>
<title><![CDATA[CSS Selectors & Specificity]]></title>
<link>http://irenaapp.de//blog-css-selectors/</link>
<guid>http://irenaapp.de//blog-css-selectors/</guid>
<pubDate>Sun, 11 Aug 2019 23:17:00 GMT</pubDate>
<description><![CDATA[CSS Selector Overview There are multiple ways to select the elements you’re trying to style in CSS. Let’s start by reviewing all the options…]]></description>
<content:encoded><![CDATA[<h3>CSS Selector Overview</h3>
<p>There are multiple ways to select the elements you’re trying to style in CSS. Let’s start by reviewing all the options.</p>
<p><strong>Type Selectors:</strong>
Select your intended element by using its element type. For example, to select all your <code><p></code>tags, use <strong>p</strong> in your CSS style sheet.</p>
<p><strong>Pseudo-Elements:</strong></p>
<p>As the name suggests, pseudo-elements are not elements themselves but allow you to select part of your HTML relative to another selector. For example, select the first letter of each paragraph with p::first-letter.</p>
<p><strong>Class Selectors:</strong></p>
<p>Elements can have multiple classes set on them to be selected in your CSS style sheet. For example,<code><h1 class='header'></code>can be selected with .header. Multiple elements can have the same class applied to them.</p>
<p><strong>Attribute Selectors:</strong></p>
<p>Select elements that have a specific type of attribute applied to them. For example, select inputs that accept numbers only with <code>input[type='number']</code>.</p>
<p><strong>Pseudo-Classes</strong>:</p>
<p>Select elements based on the CSS state they’re in. For example, style the hovered state of a button with button:hover. Check out these previous tutorials on the <strong><code>:target</code>, <code>:hover</code> and <code>:active</code> pseudo-classes</strong> to learn more.</p>
<p><strong>ID Selectors:</strong></p>
<p>Select a specific element with its unique ID. There can only be one element with each ID, whereas classes can be applied to multiple elements. For example, select <strong><code><h1 id='mainHeader'></code></strong> with #mainHeader.</p>
<p><strong>Inline Styles:</strong></p>
<p>Inline styles are applied to elements directly with the style attribute so you don’t actually use any CSS selectors. For example, you can make your header font color blue directly with <strong><code><h1 style='color: blue;'></code></strong></p>
<h3>👉 CSS Selectors and Their “Weights”</h3>
<p>Each type of selector listed above has a weight. All of these can be divided into four main groups:</p>
<p><strong><style="color:red"><code>lowest weight</code></style></strong>: type and pseudo-element selectors</p>
<p><strong><code>low weight</code></strong>: class, attribute, and pseudo-class selectors</p>
<p><strong><code>medium weight</code></strong>: ID selectors</p>
<p><strong><code>high weight</code></strong>: inline styling</p>
<p>If styles of differing weights are applied to the same element, the styling with the higher weight will be applied. If styles of even weights are applied, the styles that come last (nearest to the end of your style sheet) will be applied. This is due to the “cascading” effect of CSS (Cascading Style Sheets).</p>
<p>When two selectors of the same weight are applied to an element, it counts as 2x the weight. So, for example, an element selected with two classes will have a higher weight than just one in your CSS.</p>
<pre><code class="language-css">.gator.cayman {
// two classes
color: purple;
}
.gator {
// one class
color: purple;
}
</code></pre>
<h3>The 🛑 Problem with Competing Selectors</h3>
<p>👉 Understanding that different selectors have different weights is crucial for getting your CSS organized. But what if it’s not clear what has a higher weight?</p>
<p>Let’s say we have a paragraph that has two completing blocks of CSS: one with three matching classes and another block with a type attribute and two matching classes.</p>
<p>For example, let’s take this input with three classes and a number type attribute applied to it.</p>
<pre><code class="language-html"><input type="number" class="gator cayman reptile" />
</code></pre>
<p>If we apply these competing selectors (three matching classes vs. two matching classes and an attribute), which one will get applied?</p>
<pre><code class="language-css">.gator.cayman.reptile {
color: purple;
}
[type='number'].gator.cayman {
color: green;
}
</code></pre>
<p>👉 In this case, the “weight” of both blocks is completely even. Attribute selectors and class selectors have the same weight and each block has three of them in total. Since they’re even, we rely on the cascading effect of CSS. The last one gets applied and the input font color will be green.</p>
<p>This gets a little more complicated when you have selectors of different weights getting mixed, though.</p>
<p>Let’s update our input to have an ID, which has a higher weight than classes and attributes.</p>
<pre><code class="language-html"><input type="number" id="gatorInput" class="gator cayman reptile" />
</code></pre>
<p>Article is under construction .... To be continued...</p>]]></content:encoded>
</item>
<item>
<title><![CDATA[React advanced topics state and context architectur]]></title>
<link>http://irenaapp.de//blog-react-advvanced-state/</link>
<guid>http://irenaapp.de//blog-react-advvanced-state/</guid>
<pubDate>Wed, 13 Jun 2018 14:37:00 GMT</pubDate>
<description><![CDATA[React Advanced Topics: State and Context Architecture React has revolutionized the way we build UIs, making component-based development the…]]></description>
<content:encoded><![CDATA[<h2>React Advanced Topics: State and Context Architecture</h2>
<p>React has revolutionized the way we build UIs, making component-based development the standard. But as applications grow, managing state effectively becomes critical to avoid performance pitfalls, prop drilling, and spaghetti code. In this post, we’ll deep dive into <strong>state management</strong> and <strong>context architecture</strong>.</p>
<p>React has fundamentally changed how we build web interfaces, turning the UI into a declarative, component-driven system. But while creating simple components is straightforward, scaling your application efficiently is another story. As your app grows, managing state—knowing where data lives, how it flows, and how components communicate—becomes one of the most challenging aspects of frontend development. Prop drilling, inconsistent updates, and tangled state hierarchies can quickly turn a clean codebase into a maintenance nightmare.</p>
<p>This is where advanced state management and the Context API come into play. State isn’t just about holding data; it’s about structuring your components for clarity, reusability, and performance. Context, introduced in React 16.3, allows you to share data across the component tree without the overhead of passing props at every level. Together, a well-thought-out state architecture and context usage can transform your React apps from brittle and repetitive to scalable and elegant.</p>
<p>In this deep dive, we’ll explore React’s state mechanisms, the nuances of <code>setState</code>, patterns for lifting and organizing state, and the practical use of Context. We’ll also discuss performance considerations and when to rely on external state libraries like Redux or MobX. By the end, you’ll have a solid understanding of how to architect React apps that are maintainable, efficient, and future-proof.</p>
<h2>1. Understanding React State</h2>
<p>State in React represents the mutable data of a component. It drives UI updates and encapsulates local component behavior.</p>
<h3>Basic Example</h3>
<pre><code class="language-jsx">class Counter extends React.Component {
constructor(props) {
super(props);
this.state = {
count: 0
};
}
increment = () => {
this.setState({ count: this.state.count + 1 });
}
render() {
return (
<div>
<p>Count: {this.state.count}</p>
<button onClick={this.increment}>Increment</button>
</div>
);
}
}
</code></pre>
<blockquote>
<p>Tip: Always use setState instead of mutating state directly. Direct mutation will not trigger a re-render.</p>
</blockquote>
<p>setState Behavior</p>
<p>setState is asynchronous, and multiple state updates can be batched:</p>
<pre><code class="language-jsx">this.setState({ count: this.state.count + 1 });
this.setState({ count: this.state.count + 1 });
// Resulting count may be +1, not +2
</code></pre>
<p>To avoid this, use the functional form:</p>
<pre><code class="language-jsx">this.setState(prevState => ({ count: prevState.count + 1 }));
</code></pre>
<h2>Component Composition and Prop Drilling</h2>
<p>As components grow, passing props deeply through the tree (prop drilling) becomes cumbersome:</p>
<pre><code class="language-jsx"><Grandparent>
<Parent>
<Child someData={this.state.someData} />
</Parent>
</Grandparent>
</code></pre>
<p>Prop drilling leads to boilerplate and tightly coupled components.</p>
<ol start="3">
<li>Introduction to Context API (Legacy)</li>
</ol>
<p>React 16.3 introduced the new Context API, replacing the old unstable API. Context allows passing data through the component tree without manually passing props.</p>
<p>Basic Context Example</p>
<pre><code class="language-jsx">const ThemeContext = React.createContext('light');
class App extends React.Component {
render() {
return (
<ThemeContext.Provider value="dark">
<Toolbar />
</ThemeContext.Provider>
);
}
}
function Toolbar() {
return (
<ThemeContext.Consumer>
{theme => <div className={theme}>Toolbar with {theme} theme</div>}
</ThemeContext.Consumer>
);
}
</code></pre>
<blockquote>
<p>Note: The Provider component wraps any subtree, making the value accessible to all nested consumers.</p>
</blockquote>
<h2>State Architecture Patterns</h2>
<p>Large applications require structured state management. Here are some patterns common in 2018:</p>
<p>Lifting State Up</p>
<p>Centralize state in the nearest common ancestor to avoid duplication:</p>
<pre><code class="language-jsx">class Parent extends React.Component {
state = { sharedData: 'Hello' };
render() {
return (
<div>
<ChildA data={this.state.sharedData} />
<ChildB data={this.state.sharedData} />
</div>
);
}
}
</code></pre>
<p>Smart vs Dumb Components</p>
<p>Smart (Container) components: manage state, API calls, and business logic.</p>
<p>Dumb (Presentational) components: only render UI based on props.</p>
<pre><code class="language-jsx">
// Dumb component
const Button = ({ label, onClick }) => <button onClick={onClick}>{label}</button>;
// Smart component
class Counter extends React.Component {
state = { count: 0 };
increment = () => this.setState({ count: this.state.count + 1 });
render() {
return <Button label={`Count: ${this.state.count}`} onClick={this.increment} />;
}
}
</code></pre>
<p>Using Context for Global State</p>
<p>Instead of passing props down multiple levels, context can hold theme, auth, or settings:</p>
<pre><code class="language-jsx">
const AuthContext = React.createContext();
class App extends React.Component {
state = { isLoggedIn: false };
render() {
return (
<AuthContext.Provider value={{
isLoggedIn: this.state.isLoggedIn,
login: () => this.setState({ isLoggedIn: true })
}}>
<Navbar />
</AuthContext.Provider>
);
}
}
function Navbar() {
return (
<AuthContext.Consumer>
{({ isLoggedIn, login }) => (
<div>
{isLoggedIn ? 'Welcome!' : <button onClick={login}>Login</button>}
</div>
)}
</AuthContext.Consumer>
);
}
</code></pre>
<h3>Performance Considerations</h3>
<p>Avoid unnecessary re-renders: Use shouldComponentUpdate or PureComponent.</p>
<p>Memoize expensive computations: with memoize-one or caching.</p>
<p>Split state wisely: keeping unrelated state separate reduces re-rendering entire trees.
Summary</p>
<p>React state and context architecture in 2018 involved:</p>
<ul>
<li>
<p>Class-based components and setState</p>
</li>
<li>
<p>Lifting state up and smart/dumb separation</p>
</li>
<li>
<p>Using Context API for prop drilling avoidance</p>
</li>
<li>
<p>Performance tuning with PureComponent and shouldComponentUpdate</p>
</li>
<li>
<p>Knowing when to adopt Redux/MobX for large-scale state</p>
</li>
</ul>
<p>By structuring state and context properly, React applications can scale elegantly without becoming unmaintainable.</p>]]></content:encoded>
</item>
<item>
<title><![CDATA[Taming Prop Drilling in React: Advanced State and Context Patterns]]></title>
<link>http://irenaapp.de//blog-react-prop-drilling/</link>
<guid>http://irenaapp.de//blog-react-prop-drilling/</guid>
<pubDate>Wed, 13 Jun 2018 14:37:00 GMT</pubDate>
<description><![CDATA[Taming Prop Drilling in React: Advanced State and Context Patterns If you've been building React apps for a while, you know that one of the…]]></description>
<content:encoded><![CDATA[<h1>Taming Prop Drilling in React: Advanced State and Context Patterns</h1>
<p>If you've been building React apps for a while, you know that one of the first “growing pains” comes when your components need data from distant parts of the tree. You start passing props from parent to child, down to grandchildren, and suddenly your components are littered with props that serve no purpose other than passing them along. This phenomenon, commonly called <strong>prop drilling</strong>, can make your app brittle, repetitive, and hard to maintain.</p>
<p>In 2018, the React community was grappling with this exact challenge. While the framework itself encouraged component composition and local state, large applications exposed limitations in prop propagation. Let's explore the patterns and tools that were available to developers back then to tame prop drilling and structure state more elegantly.</p>
<hr>
<h2>Understanding Prop Drilling</h2>
<p>Prop drilling occurs when a parent component passes data to a deeply nested child that doesn’t directly need it, except to pass it further down:</p>
<pre><code class="language-jsx">class App extends React.Component {
state = { theme: 'dark' };
render() {
return <Page theme={this.state.theme} />;
}
}
function Page({ theme }) {
return <Toolbar theme={theme} />;
}
function Toolbar({ theme }) {
return <Button theme={theme} />;
}
function Button({ theme }) {
return <button className={theme}>Click Me</button>;
}
</code></pre>
<h2>Lifting State Up: The First Line of Defense</h2>
<p>The earliest solution in React is lifting state up to a common ancestor. This reduces duplication and ensures that multiple children can access the same state. However, lifting state alone doesn’t solve deep tree problems—it just centralizes state at a higher level.</p>
<pre><code class="language-jsx">
class Parent extends React.Component {
state = { user: 'Alice' };
render() {
return (
<div>
<Header user={this.state.user} />
<Content user={this.state.user} />
</div>
);
}
}
</code></pre>
<p>While effective for small trees, lifting state can still lead to verbose prop passing when children are nested multiple layers deep.
Smart vs Dumb Components</p>
<p>Another pattern that gained traction in 2018 is the smart vs dumb component separation:</p>
<p>Smart (Container) Components: Handle state, API calls, and business logic.</p>
<p>Dumb (Presentational) Components: Focus solely on rendering UI, based on props.</p>
<pre><code class="language-jsx">// Dumb component
const UserBadge = ({ name }) => <span>{name}</span>;
// Smart component
class Header extends React.Component {
state = { user: 'Alice' };
render() {
return <UserBadge name={this.state.user} />;
}
}
</code></pre>
<p>This pattern reduces prop drilling by isolating stateful logic in containers and keeping presentation simple.</p>
<p>Context API: The Official React Solution</p>
<p>Before React 16.3, context was unstable and rarely used. Passing props through multiple levels remained the default solution. With the new Context API (React 16.3+), React offered a stable way to provide data to nested components without prop drilling.
Example: Theme Context</p>
<pre><code class="language-jsx">
const ThemeContext = React.createContext('light');
class App extends React.Component {
state = { theme: 'dark' };
render() {
return (
<ThemeContext.Provider value={this.state.theme}>
<Toolbar />
</ThemeContext.Provider>
);
}
}
function Toolbar() {
return (
<ThemeContext.Consumer>
{theme => <button className={theme}>Click Me</button>}
</ThemeContext.Consumer>
);
}
</code></pre>
<p>With Provider and Consumer, any component in the tree can access the value directly, eliminating the need to pass props manually at every level.</p>
<p>Performance Considerations</p>
<p>While Context is powerful, it comes with caveats. In 2018, developers noticed:</p>
<p>Every consumer re-renders when the context value changes.</p>
<p>Large trees may suffer performance issues if context updates frequently.</p>
<p>Tips from the community included:</p>
<p>Splitting contexts for different types of data (theme, auth, settings)</p>
<p>Memoizing heavy components</p>
<p>Using PureComponent or shouldComponentUpdate to prevent unnecessary re-renders</p>]]></content:encoded>
</item>
<item>
<title><![CDATA[Learn Bash Scripting]]></title>
<link>http://irenaapp.de//blog-bash-post/</link>
<guid>http://irenaapp.de//blog-bash-post/</guid>
<pubDate>Mon, 18 Sep 2017 23:19:51 GMT</pubDate>
<description><![CDATA[Introduction to Bash Bash (or shell) scripting is a great way to automate repetitive tasks and can save you a ton of time as a developer…]]></description>
<content:encoded><![CDATA[<h4>Introduction to Bash</h4>
<p>Bash (or shell) scripting is a great way to automate repetitive tasks and can save you a ton of time as a developer. Bash scripts execute within a Bash shell interpreter terminal.
Bash is a Unix shell, which is a command line interface (CLI) for interacting with an operating system (OS). Any command that you can run from the command line can be used in a bash script. Scripts are used to run a series of commands. It is available by default on Linux and macOS operating systems.</p>
<h3>Variables</h3>
<p>In Linux shell scripting two types of variables are used: <br>
<strong>System Defined Variables & User Defined Variables.</strong></p>
<p>👉 <strong>A variable in a shell script is a means of referencing a numeric or character value.</strong> And unlike formal programming languages, a shell script doesn’t require you to declare a type for your variables.</p>
<p>To Print the value of above variables, use <code>echo</code> command as shown below :</p>
<pre><code class="language-bash"># echo $HOME
# echo $USERNAME
</code></pre>
<p>Within bash scripts (or the terminal for that matter), variables are declared by setting the variable name equal to another value.</p>
<p>We can tap into these environment variables from within your scripts by using the environment variable’s name preceded by a dollar sign. This is demonstrated in the following script:</p>
<pre><code class="language-bash">
$ cat myscript
#!/bin/bash
# display user information from the system.
echo “User info for userid: $USER”
echo UID: $UID
echo HOME: $HOME
</code></pre>
<p>Notice that the environment variables in the echo commands are replaced by their current values when the script is run. Also notice that we were able to place the $USER system variable within the double quotation marks in the first string, and the shell script was still able to figure out what we meant. There is a drawback to using this method, however. Look at what happens in this example:</p>
<pre><code class="language-bash">$ echo “The cost of the item is $15”
The cost of the item is 5
</code></pre>
<p>Whenever the script sees a dollar sign within quotes, it assumes you’re referencing a variable. In this example the script attempted to display the variable $1 (which was not defined), and then the number 5. To display an actual dollar sign, you must precede it with a backslash character:</p>
<pre><code class="language-bash">
$ echo “The cost of the item is \$15”
The cost of the item is $15
</code></pre>
<p>👉 The backslash allowed the shell script to interpret the dollar sign as an actual dollar sign, and not a variable.</p>
<h3>Strings</h3>
<h3>conditionals</h3>
<p>When bash scripting, you can use conditionals to control which set of commands within the script run. Use if to start the conditional, followed by the condition in square brackets ([ ]).</p>
<h3>Loops</h3>
<p>There are 3 different ways to loop within a bash script: for, while and until. A for loop is used to iterate through a list and execute an action at each step.</p>
<h3>Arrays</h3>
<p>Bash provided one-dimensional array variables. Any variable can be used as an array. the declare built-in will explicitly declare an array. There is no maximum limit on the size of an array, nor any requirements that members be indexed or assigned contiguously. <strong>Arrays are zero-based.</strong></p>
<h3>Comparison</h3>
<h3>User Inputs</h3>
<p>To make bash scripts more useful, we need to be able to access data external to the bash script file itself. The first way to do this is by prompting the user for input.</p>
<h3>Aliases - what are they?</h3>
<p>👉 Aliases allow a string to be substituted for a word when it is used as the first word of a simple command. The shell maintains a list of aliases that may be set and unset with the <strong>alias</strong> and <strong>unalias</strong> commands.</p>
<p>👉 Bash always reads at least one complete line of input before executing any of the commands on that line. Aliases are expanded when a command is read, not when it is executed. Therefore, an alias definition appearing on the same line as another command does not take effect until the next line of input is read. <strong>The commands following the alias definition on that line are not affected by the new alias.</strong></p>
<p>🛑 <strong>Alias are expended when the function definition is read, not when the function is executed,</strong> because a function definition itself is a compound command. As a consequence, aliases defined in a function are not available until after that function is executed. **</p>
<p>You can set up aliases for your bash scripts within your .bashrc or <code>.bash_profile</code>file to allow calling your scripts without the full filename.</p>
<h3>Shell built-in commands</h3>
<p>Built-in commands are contained within the shell itself. When the name of a built in command is used as the first word of a simple command, the shell executes the command directly, without creating a new process. Built-in commands are necessary to implement functionality impossible or inconvenient to obtain with separate utilities.</p>
<h3>3 types of built-in commands are supported by Bash:</h3>
<ol>
<li>Bourne Shell built-ins:</li>
</ol>
<p><code>break</code>, <code>cd</code>, <code>continue</code>, <code>eval</code>, <code>exec</code>, <code>exit</code>, <code>export</code>, <code>getopts</code>, <code>hash</code>, <code>pwd</code>, <code>readonly</code>, <code>return</code>, <code>set</code>, <code>shift</code>, <code>test</code>, <code>times</code>, <code>trap</code>, <code>unmask</code> and <code>unset</code></p>
<ol start="2">
<li>Bash built-in commands:</li>
</ol>
<p><code>alias</code>, <code>bind</code>, <code>builtin</code>, <code>command</code>, <code>declare</code>, <code>echo</code>, <code>enable</code>, <code>help</code>, <code>let</code>, <code>logout</code>, <code>local</code>, <code>printf</code>, <code>read</code>, <code>type</code>, <code>shopt</code>, <code>typeset</code>, <code>ulimit</code> , <code>unalias</code>,</p>
<h3>Shell execution - Executing programs from a script</h3>
<p>When a program being executed is a shell script, bash will create a new bash precess using a <strong>fork</strong>.</p>
<pre><code class="language-bash">$ echo "Hello, $(whoami)!"
</code></pre>
<h3>How to create a bash built script</h3>
<p>With the command <code>touch</code>you can create a file.</p>
<pre><code class="language-bash">$ touch hello-everybody
</code></pre>]]></content:encoded>
</item>
</channel>
</rss>