Search
30 results for “hooks”
Search results
React Hooks Deep Dive
How useState, useEffect, useMemo, and useCallback actually work under the hood, plus the dependency-array and stale-closure pitfalls that trip up most React code.
Why does React require hooks to be called in the same order on every render?
React does not track hook state by name; it tracks it by call order in a linked list attached to the component's fiber. On each render, React walks that list and matches the nth useState call to the nth stored slot. If a hook is called conditionally (inside an if, or after an early return), the call order can shift between renders, and React ends up reading the wrong slot for a given hook; this is exactly why hooks cannot be called inside conditionals or loops.
What is a stale closure and how does it happen with useEffect?
A stale closure happens when a function captures a variable from a render that is no longer current, because the effect or callback was not re-created when that variable changed. Classic case: an effect with an empty dependency array reads a piece of state, since the effect only runs once, the function it closes over always sees the state value from the first render, not the latest one. The fix is to include the variable in the dependency array (or use a functional state update that does not need to read the outer value at all).
When should you reach for useMemo or useCallback, and when is it wasted effort?
They are worth it when a computation is genuinely expensive, or when the memoized value/function is a dependency of another hook, or a prop to a component wrapped in React.memo, in those cases, an unnecessary new reference on every render causes real extra work downstream. For cheap computations with no memoized consumer, useMemo/useCallback add overhead (the comparison itself, plus code complexity) without a measurable benefit, profile before reaching for them by default.
When does semantic search (via embeddings) actually outperform traditional keyword search, and when might keyword search still win?
Semantic search wins when a query and the relevant document use different words for the same idea, "car won't start" matching a document about "vehicle fails to ignite", since embeddings compare meaning rather than literal tokens, which keyword search cannot do at all. Keyword search still wins, or at least remains necessary, for exact-match needs, an error code, a product SKU, a specific proper noun, where the literal string matters and a semantically "close" but textually different result is actually the wrong answer. This is why production search systems commonly combine both (hybrid search) rather than treating embeddings as a strict replacement for keyword matching.
How does a Network Security Group (NSG) evaluate traffic rules?
An NSG contains a prioritized list of allow/deny rules, evaluated in priority order (lowest number first) until the first rule matching the traffic's source, destination, port, and protocol is found, that rule's action wins, and no further rules are evaluated. NSGs can attach to a subnet, a network interface, or both, and are stateful, meaning an allowed inbound connection's return traffic is automatically permitted without needing a matching outbound rule. Because evaluation stops at first match, rule priority ordering is the actual logic, a broad allow rule placed before a specific deny rule silently makes that deny unreachable.
How does Kubernetes RBAC decide whether a request is allowed, and can you write an explicit deny rule?
RBAC is default-deny and purely additive: a request is denied unless some Role/RoleBinding or ClusterRole/ClusterRoleBinding explicitly grants it, and there is no such thing as an explicit deny rule. Every applicable binding's permissions are unioned together, so restricting access means removing a grant (or removing the subject from a binding), not adding a deny statement on top of an existing grant, an approach that works cleanly for grant-based access but has no mechanism for "allow everything except X" within RBAC itself.
How does a load balancer detect and handle an unhealthy backend server?
Via health checks, periodic requests (a lightweight HTTP endpoint like /healthz, or a TCP connection check) sent to each backend on an interval. A server that fails a configurable number of consecutive checks is marked unhealthy and removed from the rotation; it is added back only after passing a configurable number of consecutive successful checks, which avoids flapping a server in and out of rotation on a single transient failure.
Linux Foundations (Beginner): How Linux Really Works - Not Just Commands
Most beginners learn Linux backwards.
Why are IAM roles preferred over long-lived access keys for workloads running on EC2 or Lambda?
A long-lived access key is a static secret that must be stored somewhere, an environment variable, a config file, a secrets manager, and rotated manually or via automation; if it leaks, it remains valid until someone notices and revokes it. An IAM role attached to an EC2 instance profile or a Lambda execution role is assumed automatically by the AWS SDK, yielding short-lived credentials that are rotated transparently and expire on their own even if never explicitly revoked. This removes the entire class of "leaked long-lived credential" risk for workloads that run on AWS compute, which is why roles are the default recommendation over access keys whenever the workload runs inside AWS.
Two transactions each update two of the same two accounts, but in opposite order, and deadlock. What's the actual fix, not just for this pair of transactions, but for the application generally?
The deadlock happens because Transaction 1 locks account A then waits for account B, while Transaction 2 locks account B then waits for account A, a circular wait. The general fix isn't retry logic alone, retries only paper over deadlocks that keep recurring, it's acquiring locks on multiple objects in the same, consistent order everywhere in the application (for example, always locking accounts in ascending id order), which makes the circular-wait pattern structurally impossible rather than merely less frequent. Retry logic is still worth having as a safety net, but consistent lock ordering is what actually eliminates this class of deadlock.
What does hashed sharding trade away in exchange for fixing the monotonic-key hot-shard problem?
Hashed sharding computes a hash of the shard key value and assigns chunks by hash range instead of by the raw value, which scatters even monotonically increasing keys roughly evenly across shards, since consecutive input values hash to essentially unrelated output values. The trade-off is range-query locality: a query filtering a range of the original shard key values (like "the last 24 hours" on a timestamp key) can no longer be routed to one contiguous set of shards, because the corresponding hashed values are scattered unpredictably across the whole cluster, turning what would have been a single-shard query under range sharding into a broadcast query touching every shard.
A client sends a payment request, the network times out before a response arrives, and the client retries with the same idempotency key. What actually happens on the server?
If the original request already completed (successfully or even with an error like a 500) before the retry arrives, the server returns the exact same result it returned (or would have returned) the first time, the same status code and response body, without re-executing the underlying operation, so the customer isn't charged twice just because the client never saw the first response. This is the entire point of an idempotency key: it lets a client safely retry an operation whose actual outcome it's genuinely uncertain about (did the first request even reach the server? did it complete before the timeout?) without that retry risking a duplicate side effect.
What does a service mesh add on top of what Kubernetes Services already provide?
A Kubernetes Service provides basic load-balanced routing to a set of Pods by label selector, that's it. A service mesh intercepts every request in and out of a Pod (via a sidecar proxy) to add a uniform layer of capabilities across all services without changing application code: mutual TLS encryption between services, fine-grained traffic control (canary percentages, retries, timeouts, circuit breaking), and rich per-request observability (latency, error rate, and request volume between every pair of services). Services give you connectivity; a mesh gives you control and visibility over that connectivity.
MongoDB can be configured to behave more like a CP system or more like an AP system. What settings make that choice, and what are they actually trading?
Write concern and read preference are the actual levers: a write concern requiring acknowledgment from a majority of replicas favors consistency, a write isn't considered successful until enough nodes agree, at the cost of availability if too many nodes are unreachable during a partition. A looser write concern, or reading from secondaries that might lag behind the primary, favors availability, operations keep succeeding even when full replica agreement isn't achievable, at the cost of potentially reading or acknowledging data that isn't fully consistent across the cluster yet. This is exactly the CP-versus-AP trade-off CAP describes, expressed as a concrete, tunable configuration rather than an abstract theorem.
A custom dropdown built entirely from styled divs passes a visual design review. What is likely still broken for a keyboard-only or screen-reader user, and why doesn't looking right catch it?
Without the correct ARIA roles/states (or, better, a native `<select>`), a div-based dropdown typically has no way to be reached or operated via keyboard alone (no built-in Tab/Enter/Arrow-key handling), and a screen reader has no semantic information telling it "this is a dropdown, it is currently closed, here are its options," so it may announce nothing meaningful at all. A purely visual review can't catch this because the div looks and behaves correctly with a mouse, the missing behavior only surfaces via keyboard navigation or assistive technology, which is exactly why accessibility has to be tested directly with a keyboard and a screen reader, not inferred from how a component looks.
Linux Core Operations: Full Hands‑On Practical Labs for Users, Permissions, sudo, Packages & Services
Linux Core Operations: Full Practical Labs (Beginner → Intermediate)
What does "overlapping subproblems" mean, and why does dynamic programming provide no benefit for a problem that lacks it?
Overlapping subproblems means the same smaller subproblem genuinely recurs multiple times across different branches of the larger problem's recursive structure, exactly what makes caching valuable, the second and later occurrences become free lookups. A problem like standard mergesort, by contrast, has no overlapping subproblems, every recursive call operates on a genuinely distinct slice of the array that never recurs anywhere else, so there is nothing to cache and memoization adds only overhead (cache storage and lookup cost) with zero reuse to offset it. Recognizing whether a problem's recursive breakdown actually revisits the same subproblems is the real prerequisite for dynamic programming to help at all.
How does GitOps make rollbacks different from a traditional deployment rollback?
In a traditional deploy, rolling back means re-running a deployment process with an older artifact reference, a distinct operation from a normal deploy. In GitOps, a rollback is just a Git revert: since the desired cluster state is fully described by the repository at any commit, reverting to a previous commit and letting the reconciliation loop pick it up produces the previous cluster state through the exact same mechanism as any other change. There is no separate "rollback pipeline" to maintain or that can itself have bugs.
How to Configure Desktop Backgrounds, Power Settings, and Legal Notices Using Group Policy
In this lab, I implemented key Group Policy configurations to standardize system behavior, improve user experience, and strengthen security awareness across all domain joined devices. The configuration focuses on: Enforcing a consistent and professional desktop environment Preventing unauthorized o…
Python Web Frameworks Overview
How Flask, Django, and FastAPI trade minimalism, batteries-included structure, and async-first design differently, and how to actually choose based on project shape.
What does AKS (Azure Kubernetes Service) manage for you compared to running Kubernetes yourself on VMs?
AKS manages the Kubernetes control plane (API server, etcd, scheduler) at no direct cost for the control plane itself; you only pay for the worker nodes, which still run as VMs you have some visibility into but don't have to manually install or upgrade Kubernetes onto. Running Kubernetes yourself on plain VMs means standing up and maintaining the entire control plane, including its high availability and upgrade process, which is a substantial and ongoing operational burden. AKS trades some control-plane visibility for removing that burden, which is why it's the default choice for running Kubernetes on Azure unless there's a specific reason to self-manage.
Why does effective incident investigation in Azure usually require writing KQL rather than relying only on dashboards?
Dashboards are built in advance for questions someone anticipated asking; they're monitoring, not investigation. A real incident usually raises a question nobody built a dashboard for ("which specific requests failed, and what did they have in common?"), and answering that requires querying the underlying log data directly. KQL is Log Analytics' query language, and being able to write ad hoc queries, joining traces, filtering by custom dimensions, correlating across data types, is what turns "I can see something is wrong" into "I know why," which is the actual goal of observability, not just monitoring.
What is the difference between Blob Storage, File Storage, and Disk Storage in Azure?
Blob Storage is object storage for unstructured data (images, backups, logs), accessed via HTTP/HTTPS APIs, not mounted as a filesystem. File Storage provides fully managed file shares accessible via the SMB or NFS protocol, usable as a network drive that multiple VMs can mount simultaneously. Disk Storage provides block-level storage attached to a single VM, functioning as its virtual hard disk. The choice depends on access pattern: Blob for API-driven unstructured data at scale, File for shared network-drive-style access across machines, Disk for a VM's own persistent local-feeling storage.
What is the difference between a reserved/committed-use discount and a spot/preemptible instance, and when does each make sense?
A committed-use discount (reserved instances, savings plans) trades a usage commitment, a fixed amount of spend or capacity over a term, typically one or three years, for a significant price reduction on workloads you know will run continuously. Spot/preemptible instances offer a much steeper discount in exchange for the provider being able to reclaim the capacity with little notice, making them suitable only for interruption-tolerant workloads (batch jobs, stateless workers, CI runners) rather than anything requiring guaranteed uptime. Committed-use addresses predictable steady-state load; spot addresses flexible, interruption-tolerant load, using either for the wrong workload type either wastes the discount or causes outages.
Why does a naive `hash(key) % N` scheme for distributing keys across N servers fall apart the moment a server is added or removed?
With plain modulo hashing, the server a key maps to depends directly on the current value of N, since almost every key's `hash(key) % N` result changes the instant N changes to N-1 or N+1, even though the underlying hash values themselves didn't change at all. That means adding or removing a single server can remap the overwhelming majority of keys to different servers simultaneously, which for a cache means a massive wave of cache misses, and for a sharded store means a massive, unnecessary data-migration event, triggered by a change to just one server out of many.
Why does Docker's official build guidance recommend running as a non-root user inside a container, and why not just use sudo when root is needed?
Running as root inside a container means that a successful application-level compromise (a code-execution vulnerability, an unsafely deserialized payload) hands the attacker root inside that container immediately, with no privilege-escalation step required, and depending on the container runtime's configuration, root inside a container can sometimes be leveraged toward the host. Creating a dedicated non-root user via `USER` in the Dockerfile means a compromise still has to escalate privileges to do serious damage. `sudo` is specifically discouraged in Docker's own guidance because of its unpredictable TTY and signal-forwarding behavior inside a container, not because privilege separation itself is unnecessary.
What is a shard key, and why does a low-cardinality shard key (few distinct values) cause a hot shard?
A shard key is the field (or fields) a sharded database uses to decide which shard each document or row actually lives on. If that field has few distinct values, say `country`, and the real data is skewed (80% of users in one country), the vast majority of documents route to the same shard regardless of how many shards exist in the cluster, overwhelming it with disproportionate read/write load and storage while other shards sit comparatively idle. Cardinality alone doesn't guarantee even distribution either, the values also need to actually occur with reasonably even frequency in the real data, not just theoretically have many possible values.
Why does using a monotonically increasing field (a sequential ID, a timestamp) as a shard key concentrate all new writes onto one shard, even with range-based sharding across many shards?
With range-based sharding, chunks are assigned contiguous ranges of shard-key values, and a monotonically increasing key means every new document's value is higher than every previously inserted one, so all new inserts land in whatever chunk currently owns the highest range, which lives on one specific shard. Every other shard, holding older, lower-valued ranges, receives none of the new write traffic at all, the exact "hot shard" problem, all insert load concentrated on a single shard regardless of how many total shards the cluster has.
What is the required contract between equality and hashing for an object used as a dictionary key, and why does the hash table need it specifically?
The contract is one-directional but strict: if two objects compare equal, they must produce the same hash value. A hash table uses an object's hash to pick which bucket to look in, then uses equality only to confirm the exact match within that bucket, so if two equal objects hashed differently, a lookup for one would search the wrong bucket entirely and never even reach the equality check that would have confirmed the match. The hash doesn't have to be unique across unequal objects (collisions are expected and handled), it just has to agree for anything that compares equal, that's the one property the whole lookup mechanism depends on.