<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Jack Houk on Medium]]></title>
        <description><![CDATA[Stories by Jack Houk on Medium]]></description>
        <link>https://medium.com/@jack.l.houk?source=rss-72a54c97d45e------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*dFp-Im7Ok2vNWDOZKxTFUw.jpeg</url>
            <title>Stories by Jack Houk on Medium</title>
            <link>https://medium.com/@jack.l.houk?source=rss-72a54c97d45e------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 17 Nov 2026 05:41:11 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@jack.l.houk/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Maximizing the Power of RTK Query with onQueryStarted]]></title>
            <link>https://medium.com/@jack.l.houk/maximizing-the-power-of-rtk-query-with-onquerystarted-e2c6e76b75d1?source=rss-72a54c97d45e------2</link>
            <guid isPermaLink="false">https://medium.com/p/e2c6e76b75d1</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[redux]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[rtk-query]]></category>
            <dc:creator><![CDATA[Jack Houk]]></dc:creator>
            <pubDate>Mon, 09 Nov 2026 22:07:29 GMT</pubDate>
            <atom:updated>2026-11-09T22:20:43.919Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="Redux logo and the text “RTK Query” beside it, both in light purple on a darker background that is loosely suggestive of space" src="https://cdn-images-1.medium.com/max/700/1*UmkRCx3r7ZJnuGj5fA6J9Q.png" /></figure><p>This tutorial assumes you are familiar with the basics of RTK query. You’re fetching, mutating, transforming, and selecting with the best of them. Now you would like to incorporate dynamic query aware behavior into the lifecycle, and that’s where onQueryStarted comes in.</p><p>Every other element of RTK Query’s lifecycle is either highly opinionated, like tags, or aimed at external Redxu consumers, like lifecycle matchers. The onQueryStarted method is on site, wrapped right around the query inside RTK. For better and worse, this method will let you get deep inside the querying and caching process.</p><h4>What is onQueryStarted</h4><p>Redux <a href="https://redux.js.org/tutorials/essentials/part-8-rtk-query-advanced#the-onquerystarted-lifecycle">describes</a> onQueryStarted as a lifecycle method of an RTK mutator or query. This is technically true, but understates the power of it significantly. A more informative description might be onQueryStarted is <strong>the</strong> lifecycle method of an RTK mutator or query. It has access to the Redux store, dispatch, the query context, and a promise of query results. This means it can handle a lot of jobs.</p><figure><img alt="Flow diagram shows RTK Query wrapped fully inside onQueryStarted. Flow through RTK query is from Request Processing to Custom QueryFn to TransformResponse to Cache Update. onQueryStarted begins with Examine Request &amp; Read store, which has arrows to initiate telemetry, dispatch events, optimistic update the cache, and await the query. onQueryStarted ends by handling the RTK Query result with followup queries, cache rollback (on failure), more dispatches, and resolving telemetry" src="https://cdn-images-1.medium.com/max/745/1*rYr6gspQCjTOXos9ADsYBQ.png" /><figcaption>Not a lot of lifecycle left if we look at everything onQueryStarted could do</figcaption></figure><p>Because onQueryStarted is an async thunk, it can synchronize interactions between the query (initiation or completion) and external services. Because it receives the updateQueryData and upsertQueryData utils, it can optimistically update before the network call completes and rollback easily if it doesn’t. Because it has a complete view of the query context — with access to both the request and store — it can act as an optimistic updater for other slices.</p><p>It’s not the only approach to synchronizing and updating. Listener middleware and query matchers offer more structured alternatives for some of these behaviors, but when there is a need to retain context from query initiation through completion onQueryStarted is a fantastic and flexible tool for the job.</p><figure><img alt="A large wooden mallet poised over an egg in a egg cup, as if someone is about to try to open the egg with the mallet" src="https://cdn-images-1.medium.com/max/1024/1*k17ZJ3ULem31fAn3xYG8Sw.jpeg" /><figcaption>Things are easier when you use the right tool for the job.</figcaption></figure><p>On a more granular level, onQueryStarted is an asynchronous function that is called when an RTK query is started. It receives two arguments: the argument passed to the query it is a part of, and an RTK lifecycle API object. This second object contains <a href="https://redux.js.org/toolkit/rtk-query/api/createApi#lifecycle-api-properties">a variety of properties</a> some are usually irrelevant (like updateCachedData and requestId), but dispatch, getState, and queryFulfilled are what make onQueryStarted such a powerful tool.</p><p>These first two, dispatch and getState, will be familiar to anyone who’s written a thunk. They are exactly what they sound like; they let you dispatch to, and get the state from, the Redux store. queryFulfilled is a promise that resolves to the result of the query completion, or rejects if there is an error. This promise is what sets onQueryStarted apart from a standard query lifecycle listener: it allows us to take actions when the query is initiated and, without losing context, perform additional actions when the query completes.</p><h3>When to use onQueryStarted</h3><p>The key consideration in using onQueryStarted is whether or not you need to retain context across the query lifecycle and make decisions informed by the query result. If you just need conditional processing of the query request with access to the Redux store, you can use a <a href="https://redux.js.org/toolkit/rtk-query/api/createApi#queryfn">custom queryFn</a>. If you need to dispatch events based on query lifecycle events you can use the <a href="https://redux.js.org/toolkit/rtk-query/api/created-api/endpoints#matchers">query’s matchers</a> along with extraReducers or listener middleware. The flexibility and persistence offered by onQueryStarted could cover almost any case, but you probably don’t want it when there’s a more tailored solution. However, there is one common case where onQueryStated is the first-class solution.</p><h4>Cache Updates</h4><p>Updating the cache, generally during mutations, is <a href="https://redux.js.org/tutorials/essentials/part-8-rtk-query-advanced#optimistic-updates-for-reactions">the recommended use</a> for onQueryStarted. These updates can be <a href="https://redux.js.org/toolkit/rtk-query/usage/manual-cache-updates#optimistic-updates">optimistic</a> or <a href="https://redux.js.org/toolkit/rtk-query/usage/manual-cache-updates#pessimistic-updates">pessimistic</a>.</p><p>In the case of optimistic updating, we’re making changes to the cache pre-query based on the incoming arguments to the RTK endpoint. This means the change must be rolled back if the mutation fails, or if what’s created by the request doesn’t match what was optimistically created. Pessimistic updates wait for the request to resolve before updating the cache, so they’re slower but they don’t risk rollback. Either option will avoid stale cache entries with minimal network calls.</p><p>For performing these updates onQueryStarted should be considered the default tool. The fact that it retains context across the entire query execution makes it essential for cleanly handling optimistic updates with rollbacks. The fact that it has built in access to dispatch means it can use your slice’s slice.util actions to update or upsert in a controlled manner.</p><h4>Adding Custom Monitoring</h4><p>When detailed control over emitting telemetry is desired, onQuerystarted should be considered situationally. It’s absolutely possible to enact telemetry with matchers which might look something like this:</p><ul><li>Create listener middleware that matches the query’s matchPending to emit a “query invoked” event to a reporting service when the query becomes pending. Include the action’s request id as a trace id and the started timestamp.</li><li>Create a similar listener for matchFulfilled to report that the request resolved. Extract fulfilled timestamp and include the request id for tracing.</li></ul><blockquote>Note that matchFulfilled does not inherently mean a 2xx. The default fetch base query does not reject on a 4xx or 5xx so this matcher won’t inherently distinguish query success from failure, just that it didn’t throw.</blockquote><ul><li>Check the action.meta.baseQueryMeta.response.status in the matchFulfilled listener to determine what status to report.</li><li>If the status is a 4xx, emit an additional reporting that includes action.meta.arg.originalArgs to log what arguments generated a bad request.</li><li>Add amatchRejected listener to report query execution errors. These will still have a request id for tracing, but will lack timing information.</li></ul><p>This approach works well. We can report that a query happened, determine the status, and trace an id for it. The approach can even be applied as a generic listener for all pending/fulfilled/rejected actions for a given API slice by listening for the <a href="https://redux.js.org/tutorials/essentials/part-7-rtk-query-basics#query-arguments-and-cache-keys:~:text=the%20names%20of%20the%20actions">generic action names</a>.</p><figure><img alt="A hawk, in profile, looking at you." src="https://cdn-images-1.medium.com/max/1024/1*RhWBA6vfasbRFVnbixUihQ.jpeg" /><figcaption>Watching those queries like…some kind of bird.</figcaption></figure><p>We are, however, almost entirely reliant on the action that RTK query produces to know anything about what is going on. We even lose timing information when the query rejects. With onQueryStarted we have the ability to maintain our own stateful wrapper around the query as it runs, so we can time and trace how we want. A basic example could look like this:</p><ul><li>When the query starts, get a start timestamp and generate a custom trace id. Then emit an event to a reporting service indicating the query started. Await the query resolution.</li><li>When the query resolves, get an ending time and calculate the round trip time for the query. Examine the response payload for a status code &amp; report the status code and duration along with the trace id back to the reporting service.</li><li>If the response status is a 4xx, emit an additional report with the trace id and a log of the arguments that were passed to the query that generated a bad request.</li></ul><p>With this approach we have our own timing, and can customize how we id queries. onQueryStarted may be the right tool if that type of customization is needed, or if the consistency benefits of having a wrapper around the query are desired. In practice, the answer may not be one or the other — it is entirely possible to mix and match.</p><figure><img alt="Two slices of cake on one plate. One slice is chocolate with an orange berry on top, the other is cheesecake with raspberry sauce." src="https://cdn-images-1.medium.com/max/1024/1*g8ucD-mcT4rmWoyxjuqvAg.jpeg" /><figcaption>¿por qué no los dos?</figcaption></figure><p>A project could, for example, use generic listeners to add standardized reporting to all queries by default, and use onQueryStarted for particularly sensitive queries that need custom behavior. On smaller projects, onQueryStarted may be a better stylistic choice as well, because it locates the monitoring code directly in the definition of the API slice rather than elsewhere in a generic listener.</p><h4>Dispatching Actions Based on Query Results</h4><p>One place where readability almost always cuts in favor of using onQueryStarted over a listener, is when a specific query needs additional actions dispatched based on the results. This is conceptually similar to the cache update case, but applied more broadly. With access to dispatch and getState it is possible for onQueryStarted to compute and apply updates for any slice, not just the query cache.</p><p>Frequently in web application code, like a React component, an undesirable situation arises where the flow of behavior looks like this.</p><figure><img alt="Behavior flow chart showing a user action in “render space” dispatching an action to RTK query in “Redux space”. RTK query waits for query and leads back to Process Data in render space. Process Data creates Derived Actions which lead to store updates back on the Redux side, and Store updates finally follows an Action Applied arrow back to Redraw in Render space." src="https://cdn-images-1.medium.com/max/544/1*YGj5CjDYmuJ4js8MD-bxwQ.png" /><figcaption>Note that “Process Data” is on the wrong side of this chart</figcaption></figure><p>Processing data to update other parts of the store has absolutely nothing to do with rendering. Making the caller of the RTK query responsible for deriving store updates makes it harder to test the caller and the store. Occasionally, it results in truly absurd situations, like making a submit button responsible for pushing updates to components all over the page.</p><p>Most developers will notice that situation is unreasonable, understanding that a submit button should be a reusable component. So instead, something higher up the component tree will construct an elaborate onSubmit closure and drill it down to the button. This, at least, makes the submit button testable, but still ignores the real problem.</p><p>The fundamental problem in both of those cases, is that we are inappropriately using our rendering code as a context wrapper around the query. As we’ve seen already, RTK gives us a much better option. If we need a persistent context wrapper around a query, we have the RTK lifecycle, including onQueryStarted. With those tools, the process above can look more like this:</p><figure><img alt="Behavior flow chart showing a user action in “render space” dispatching an action to RTK query in “Redux space”. RTK query has several arrows leaving it, one to an immediate optimistic update leading to a render “Draw” action, one showing telemetry emitted to monitoring, one showing “update slices” that updates the store and triggers a re-render. Unlike the prior chart there is minimal back and forth between Render and Redux." src="https://cdn-images-1.medium.com/max/761/1*cFHfVjZdnPdfYJiEKaKWpw.png" /><figcaption>Now render can remain focused on rendering</figcaption></figure><p>Multiple parts of the RTK query lifecycle might be preferred for this workflow, depending on the specific circumstances. However, when updating the slices is tightly coupled to a single query, onQueryStarted is an effective and readable choice. In such tightly coupled cases, onQueryStarted locates derived updates directly in the endpoint definition; this reveals the tightly coupled relationship to future readers, which improves readability. Using onQueryStarted is also a natural conceptual fit: the store updates being done here are analogous to the cache updates onQueryStarted would normally be performing . Together, these reasons make onQueryStarted a top choice for this use case.</p><h3>Happy Querying</h3><p>There will always be more individual situations than could ever be covered in a guide, and they deserve individual consideration. These examples may not apply perfectly to your project, but hopefully the concepts presented empower you to make principled, technically sound decisions about using the RTK lifecycle.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e2c6e76b75d1" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>