<?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 Emmanuel Nnajiofor on Medium]]></title>
        <description><![CDATA[Stories by Emmanuel Nnajiofor on Medium]]></description>
        <link>https://medium.com/@emiklad?source=rss-7f9d555fe2bf------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*7iJ8wjfPc1nw3qzrSqLpeg.jpeg</url>
            <title>Stories by Emmanuel Nnajiofor on Medium</title>
            <link>https://medium.com/@emiklad?source=rss-7f9d555fe2bf------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 22:18:11 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@emiklad/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[How Statistical Fallacies Mislead Decision-Making: Building a Theoretical and Practical…]]></title>
            <link>https://medium.com/@emiklad/how-statistical-fallacies-mislead-decision-making-building-a-theoretical-and-practical-c046d79a036b?source=rss-7f9d555fe2bf------2</link>
            <guid isPermaLink="false">https://medium.com/p/c046d79a036b</guid>
            <category><![CDATA[statistics]]></category>
            <category><![CDATA[research]]></category>
            <category><![CDATA[policy]]></category>
            <dc:creator><![CDATA[Emmanuel Nnajiofor]]></dc:creator>
            <pubDate>Sun, 04 Oct 2026 14:57:26 GMT</pubDate>
            <atom:updated>2026-10-04T14:57:26.096Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*atUemr49mY82OGwU" /><figcaption>Photo by <a href="https://unsplash.com/@kommumikation?utm_source=medium&amp;utm_medium=referral">Mika Baumeister</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>How Statistical Fallacies Mislead Decision-Making: Building a Theoretical and Practical Framework-Part 4</h3><h3>Misreading Randomness, Chance, Models, and False Patterns</h3><p>The fallacies in this part share a different root from the first two parts. These aren’t about what data gets collected or how it gets grouped. They’re about what happens when humans and models try to make sense of randomness itself, and get it wrong in very predictable ways. Gambler’s Fallacy, Regression to the Mean, Overfitting, and the Danger of Summary Metrics all trace back to a misunderstanding of chance, variance, or complexity.</p><h3>Gambler’s Fallacy</h3><p>The Gambler’s fallacy indicates that if a series of events is random and the events are independent of one another, then the outcome of one or more events cannot influence or predict the outcome of the next event. The gambler’s fallacy consists of misjudging whether a series of events is truly random and independent. It involves wrongly concluding that the outcome of the next event will be the opposite of the outcomes of the preceding series of events. The Gambler’s fallacy also called the Monte Carlo fallacy is named after the Casino de Monte-Carlo in Monaco where it was observed in 1913. The roulette wheel’s ball had fallen on black several times in a row. This led people to believe that it would fall on red soon and they started pushing their chips, betting that the ball would fall in a red square on the next roulette wheel turn. The ball did fall on the red square, but only after a total of 26 turns. Accounts stated that millions of dollars had been lost by then.</p><p><strong>Case Study:</strong> A study published in Frontiers in Science 2013 examined how the Gambler’s Fallacy can influence clinical decision-making. Healthcare professionals, when exposed to a series of similar patient cases, agreed that they tend to incorrectly assume that a different diagnosis is due after a streak of identical diagnoses, leading to potential diagnostic errors (Lyons et al., 2013). A study featured in the National Bureau of Economic Research (NBER) found that loan officers might be influenced by the Gambler’s Fallacy during approval processes. After approving several loans consecutively, an officer might feel that a rejection is due, potentially leading to unjustified denials (Chen et al., 2016).</p><h3>Regression to the Mean Fallacy</h3><p>The regression to the mean fallacy arises in research when analysts mistakenly attribute changes in the outcome to manipulations of an experimental factor rather than observations reverting to the mean. This fallacy overlooks how unusual outcomes tend to shift towards the mean due to random chance, producing an apparent improvement. When a thing happens that’s unusually good or bad, over time it will revert back towards the average. Anywhere that random chance plays a part in the outcome, you’re likely to see regression toward the mean. For example, success in business is often a combination of both skill and luck. This means that the best performing companies today are likely to be much closer to average in 10 years’ time, not through incompetence but because today they’re likely benefitting from a string of good luck, like rolling a double-six repeatedly.</p><p><strong>Case Study:</strong> An organization observed that employees receiving the highest performance ratings tended to have lower ratings in subsequent evaluations, and vice versa. This fluctuation, due to regression to the mean, suggests that performance evaluations should consider long-term trends rather than isolated assessments. Also, a company noticed that sales teams with exceptionally high performances in one quarter often experienced declines in the next, while low performers showed improvements. This pattern, attributable to regression to the mean, cautions against making hasty decisions based solely on short-term performance metrics.</p><h3>Overfitting</h3><p>Overfitting a model is a condition where a statistical model begins to describe the random error in the data rather than the relationships between variables. This problem occurs when the model is too complex. In regression analysis, overfitting can produce misleading R-squared values, regression coefficients, and p-values. Overfit regression models have too many terms for the number of observations. When this occurs, the regression coefficients represent the noise rather than the genuine relationships in the population. Overfitting often occurs when analysts chase a high R-squared. Inflated R-squared values are a sign of overfitting models, leading to misleading results.</p><p><strong>Case Study:</strong> Overfitting is a common pitfall in developing predictive models for stock prices in the financial industry. Models that are too finely tuned to historical data may capture random market fluctuations rather than underlying trends, resulting in poor predictive performance on future data.</p><h3>Danger of Summary Metrics Fallacy</h3><p>Taking a series of data and summarizing it into a single data point like a total or average can be misleading as it only looks at the summary metrics of data sets. Statistician Francis Anscombe put together four example data sets in the 1970s to demonstrate the effect. Known as Anscombe’s Quartet, each data set has the same mean, variance and correlation. However, when graphed, it’s clear that each of the data sets is different. The point that Anscombe wanted to make is that the shape of the data is as important as the summary metrics and cannot be ignored in the analysis.</p><h3>Coming Up in Part 5</h3><p>Part 5 looks at what happens when the act of measuring something changes the very behavior you’re trying to measure: Cobra Effect, Hawthorne Effect, McNamara Fallacy, and Overgeneralization.</p><h3>References</h3><p>Barnett, A. G., Van Der Pols, J. C., &amp; Dobson, A. J. (2005). Regression to the mean: what it is and how to deal with it. <em>International journal of epidemiology, 34</em>(1), 215–220.</p><p>Chen, D. L., Moskowitz, T. J., &amp; Shue, K. (2016). “Decision Making Under the Gambler’s Fallacy: Evidence from Asylum Judges, Loan Officers, and Baseball Umpires” <em>The Quarterly Journal of Economics, vol 131</em>(3), pages 1181–1242.</p><p>Lyons, J., Weeks, D. J., &amp; Elliott, D. (2013). The gambler’s fallacy: a basic inhibitory process? <em>Front. Psychology 4</em>:72. doi: 10.3389/fpsyg.2013.00072</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c046d79a036b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How Statistical Fallacies Mislead Decision-Making: Building a Theoretical and Practical…]]></title>
            <link>https://medium.com/@emiklad/how-statistical-fallacies-mislead-decision-making-building-a-theoretical-and-practical-a45919b49c10?source=rss-7f9d555fe2bf------2</link>
            <guid isPermaLink="false">https://medium.com/p/a45919b49c10</guid>
            <category><![CDATA[statistics]]></category>
            <category><![CDATA[research]]></category>
            <category><![CDATA[healthcare]]></category>
            <dc:creator><![CDATA[Emmanuel Nnajiofor]]></dc:creator>
            <pubDate>Tue, 29 Sep 2026 02:54:18 GMT</pubDate>
            <atom:updated>2026-09-29T02:54:18.143Z</atom:updated>
            <content:encoded><![CDATA[<h3>How Statistical Fallacies Mislead Decision-Making: Building a Theoretical and Practical Framework-Part 3</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*yC7IUGvWkiXAF1wX" /><figcaption>Photo by <a href="https://unsplash.com/@kommumikation?utm_source=medium&amp;utm_medium=referral">Mika Baumeister</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>When the Data You Have Isn’t the Data You Need</h3><p>Part 2 covered fallacies about what data gets seen in the first place. This part assumes you already have the data in front of you, and shows how it can still mislead you once it gets filtered, grouped, or read for causality. Survivorship Bias, Simpson’s Paradox, False Causality, and Gerrymandering (the Modifiable Areal Unit Problem) all show up after the data collection stage, in the interpretation itself.</p><h3>Survivorship Bias</h3><p>Survivorship bias also known as Survival bias implies drawing conclusions from an incomplete dataset because that data has survived some selection criteria. When analysing data, crosschecking for left-out data is important. Sometimes, the full picture is obscured because the data you’ve got has survived a selection of some sort. Survivorship bias causes us to see incomplete pictures of reality by only looking at those who have succeeded, not those who couldn’t make it, or worse yet, didn’t even try. This leads to overly optimistic or skewed conclusions.</p><p>For example, in WWII, a team was asked where the best place was to fit armour to a plane. The planes that came back from battle had bullet holes everywhere except the engine and cockpit. The team decided it was best to fit armour where there were no bullet holes, because planes shot in those places had not returned. If a start-up only examines the success stories in its industry without accounting for failed businesses, it may misjudge the strategies required for success (Chuang, 2020).</p><p><strong>Case Study:</strong> Two hospital-based studies published in 2019 by the American Academy of Neurology found that smoking and hypertension, the two most significant risk factors for aneurysmal subarachnoid hemorrhage (aSAH), causes improved survival for patients who have suffered from aSAH. However, further research aimed at verifying these findings revealed the presence of survivorship bias. The initial studies excluded smokers with hypertension who died before reaching the hospital. In contrast, analyses that included more accurate measurements of risk factors and accounted for patients with sudden-death aSAH, those who never made it to the hospital, showed the opposite results. In these analyses, smokers exhibited reduced survival compared to non-smokers, and individuals with high systolic blood pressure (SBP) had lower survival rates compared to those with low SBP (Lindbohm et al., 2019). In entrepreneurship, focus is always on the success stories of successful brands like Apple and Microsoft thereby overestimating the likelihood of start-up success quite often. This bias overlooks the vast number of failed start-ups, potentially encouraging unrealistic expectations among new entrepreneurs.</p><h3>Simpson’s Paradox</h3><p>Simpson’s Paradox is a phenomenon in which a trend appears in different data groups but disappears or reverses when the groups are combined. It’s especially prominent in healthcare, where treatments may show different outcomes based on age or health conditions. Ignoring these nuances can result in policies that don’t benefit the target population (Pearl &amp; Mackenzie, 2018). Understanding and identifying this paradox is extremely important for correctly interpreting data. Otherwise, one is left trying to take action on superficial data trends that don’t translate into the real world.</p><p><strong>Case Study:</strong> A 2021 study, published in arXiv, analysed COVID-19 case fatality rates (CFRs) between China and Italy. Initially, Italy’s overall CFR appeared higher than China’s. However, when the data was stratified along age groups, it revealed that Italy had a higher proportion of older individuals infected, leading to a higher overall CFR. Within each age group, Italy’s CFR was lower than China’s, exemplifying Simpson’s Paradox (Von Kügelgen et al., 2021). In the 1980s, there was a study about the most effective way to treat kidney stones, using existing outcome data. When looking at the outcomes for all patients, procedure A showed better results. However, when scientists categorised the data by stone sizes (small and large stones), they found that procedure B was better for all stone sizes. This paradox arose because Treatment A was often used for more severe cases, skewing overall success rates (Sundahl, 2022).</p><h3>False Causality</h3><p>“Every time I bring my umbrella with me, it rains. Hence, if I leave it at home, there will be sunshine”. The False Causality fallacy also known as Causal fallacy or Non causa pro causa occurs when the researcher falsely assumes that when two events occur together that one must have caused the other. This fallacy arises when correlation is mistaken for causation, leading to the erroneous conclusion that one event must have caused the other simply because they are associated.</p><p><strong>Case Study:</strong> A prevalent false causality is the belief that vaccines cause autism in Children. This misconception stems from the observation that aluminum adjuvants (small amounts of aluminum added to some vaccines to help the body build stronger immunity against the germ in the vaccine) in vaccines cause inflammation and inflammation cause autism, so vaccines do cause autism through aluminum adjuvants. This arose out of the coincidence that children manifest signs of autism during the same age they receive vaccination. The notion that aluminum adjuvants cause autism because of inflammation is not sufficient by itself to establish causality. To date, no clear evidence supports the notion that autism is caused by inflammation (The Children’s Hospital of Philadelphia, 2018). Also during the COVID-19 pandemic, some conspiracy theories falsely claimed that 5G technology caused the virus. This fallacy arose from the coincidental rollout of 5G networks and the outbreak of COVID-19, leading to an incorrect causal inference. Scientific evidence has since debunked any link between 5G technology and the virus (The Children’s Hospital of Philadelphia, 2021).</p><h3>Gerrymandering</h3><p>This is the practice of deliberately manipulating boundaries of political districts in order to sway the result of an election. A similar phenomenon known as the Modifiable Areal Unit Problem (MAUP) can occur when analysing data. How one defines the areas to aggregate one’s data can change the result. For instance, what one defines as ‘Northern counties’ in a dataset could alter the outcome. The scale used to group data can also have a big impact. Results can vary wildly whether using postcodes, counties or states.</p><p><strong>Case Study:</strong> This case study examines the modifiable areal unit problem (MAUP), a type of data gerrymandering, in disease mapping. In this field, fine-resolution spatial health data (detailed information about the physical location of health-related events, which can be used to understand and predict the spread of disease and other health outcomes) are often aggregated for various reasons, such as protecting patient privacy, thereby adjusting original data boundaries. Typically, this aggregation happens only once, leading to “single-aggregation disease maps.” The representation of the underlying data in these maps is influenced by the choice of aggregation units different from the original, which is the essence of the MAUP. To address this issue, a study was conducted that employed the overlay aggregation method (OAM) on a real-world dataset of ischaemic stroke hospital admissions in Perth, Western Australia, in 2016. The OAM is a novel smoothing technique that enhances disease mapping by avoiding reliance on any single set of aggregation units. Instead, it incorporates information from multiple sets. This approach can significantly improve resource allocation efficiency compared to single-aggregation maps (Tuson et al., 2020).</p><h3>Coming Up in Part 4</h3><p>Part 4 moves from flawed inference to flawed intuition about randomness itself: Gambler’s Fallacy, Regression to the Mean, Overfitting, and the Danger of Summary Metrics.</p><h3>References</h3><p>Chuang, J. (2020). Selection Bias and the Survivorship Fallacy in Startups. <em>Journal of Business Ventures.</em></p><p>Lindbohm, J. V., Kaprio, J., &amp; Korja, M. (2019). Survival bias explains improved survival in smokers and hypertensive individuals after aSAH. <em>Neurology</em>, 10.1212/WNL.0000000000008537. doi:10.1212/wnl.0000000000008537</p><p>Pearl, J., &amp; Mackenzie, D. (2018). <em>The Book of Why: The New Science of Cause and Effect.</em> Basic Books.</p><p>Sundahl, D. (2022). Why should business care about Simpson’s paradox? — product science lab. Product Science. (2022, September 9). <a href="https://www.dx.mba/blog/%3Asimpsons-paradox?utm">https://www.dx.mba/blog/%3Asimpsons-paradox?utm</a></p><p>The Children’s Hospital of Philadelphia (2018). Logical fallacies and vaccines — what you should know. Children’s Hospital of Philadelphia. <a href="https://www.chop.edu/sites/default/files/vaccine-education-center-logical-fallacies.pdf">https://www.chop.edu/sites/default/files/vaccine-education-center-logical-fallacies.pdf</a></p><p>The Children’s Hospital of Philadelphia. (2021). News &amp; views — Name the logical Fallacy: Covid-19 Edition. Children’s Hospital of Philadelphia. <a href="https://www.chop.edu/vaccine-update-healthcare-professionals/newsletter/news-views-name-logical-fallacy-covid-19-edition?utm">https://www.chop.edu/vaccine-update-healthcare-professionals/newsletter/news-views-name-logical-fallacy-covid-19-edition?utm</a></p><p>Tuson, M., Yap, M., Kok, M. R., Boruff, B., Murray, K., Vickery, A., Turlach, B.A. &amp; Whyatt, D. (2020). Overcoming inefficiencies arising due to the impact of the modifiable areal unit problem on single-aggregation disease maps. <em>International journal of health geographics, 19</em>, 1–18.</p><p>Von Kügelgen, J., Gresele, L., &amp; Schölkopf, B. (2021). Simpson’s paradox in Covid-19 case fatality rates: a mediation analysis of age-related causal effects. <em>IEEE transactions on artificial intelligence, 2</em>(1), 18–27.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a45919b49c10" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How Statistical Fallacies Mislead Decision-Making: Building a Theoretical and Practical Framework…]]></title>
            <link>https://medium.com/@emiklad/how-statistical-fallacies-mislead-decision-making-building-a-theoretical-and-practical-framework-de78b4550890?source=rss-7f9d555fe2bf------2</link>
            <guid isPermaLink="false">https://medium.com/p/de78b4550890</guid>
            <category><![CDATA[statistics]]></category>
            <category><![CDATA[research]]></category>
            <dc:creator><![CDATA[Emmanuel Nnajiofor]]></dc:creator>
            <pubDate>Mon, 21 Sep 2026 08:49:26 GMT</pubDate>
            <atom:updated>2026-09-21T09:01:45.519Z</atom:updated>
            <content:encoded><![CDATA[<h3>How Statistical Fallacies Mislead Decision-Making: Building a Theoretical and Practical Framework- Part 2</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*be3hSCNHzFcxqmuE" /><figcaption>Photo by <a href="https://unsplash.com/@bkaraivanov?utm_source=medium&amp;utm_medium=referral">Bozhin Karaivanov</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>Part 2: Fallacies of Cherry-Picked and Suppressed Data</h3><p>The first cluster of fallacies in this series has nothing to do with how numbers are calculated. It has to do with what data even makes it into the room. Before a single statistical test is run, decisions are already being made about what gets collected, what gets reported, and what gets left out. Cherry-Picking, Data Dredging, Publication Bias, and Sampling Bias all live in that gap between the full picture and the picture someone chose to show you.</p><h3>Cherry-Picking</h3><p>Cherry-picking, also called the Fallacy of Incomplete Evidence or Suppressing Evidence, is the practice of selectively citing individual cases or pieces of data that seemingly support a particular viewpoint while ignoring a substantial amount of related information that may contradict that stance. This behaviour can occur both intentionally and unintentionally. The term draws its analogy from the act of harvesting fruit, particularly cherries, where the picker chooses only the ripest and most appealing fruits. An observer who sees only this curated selection might erroneously conclude that most of the tree’s fruits are of similar high quality or ripeness. This selective process can create a misleading impression of the overall quality since the chosen sample does not accurately represent the entirety. When receiving information from others, there is often a risk that the selected data could distort the truth to support a particular opinion. Consequently, it is essential for one to always find out what information they might be overlooking when confronted with data. Cherry-picking can lead to biased conclusions, frequently overstating the validity of a claim. This issue is prevalent across various fields, including health, finance, and policy, where complex datasets are available for analysis.</p><p><strong>Case Study:</strong> In 2022, the INFORMS Journal on Manufacturing &amp; Service Operations Management published a study addressing the market design problem within Medicare Advantage (MA), the largest risk-adjusted capitation payment program in the U.S. healthcare system. The study highlighted that the current MA capitation payment structure unintentionally incentivizes health plans to engage in “risk selection,” where they focus on enrolling more profitable patient types. MA plans typically collaborate exclusively with select healthcare providers, known as in-network providers, while covering only limited aspects of patients’ healthcare needs. Patients who seek care from out-of-network providers are not covered under these plans, leading to out-of-pocket expenses for any services not included. Consequently, many MA plans predominantly feature in-network providers that cater to straightforward and less costly medical conditions. Patients with complex health issues often face subtle barriers, such as restricted provider networks or elevated out-of-pocket costs, making it more difficult for them to enrol in MA plans. The risk-adjustment mechanism, designed to promote fairness, inadvertently encourages selective enrolment tactics. This cherry-picking behaviour is primarily driven by the desire for profit maximization, as MA plans aim to enrol patients who are less costly to treat. Although MA health plans report impressive annual patient volumes, these figures often reflect a higher number of relatively healthy individuals rather than those with significant health challenges, underscoring the issue of cherry-picking in patient enrolment (She et al., 2022).</p><h3>Data Dredging</h3><p>Data dredging also known as Data Dredging, Data Fishing, Data Snooping, Data Butchery or p-hacking refers to the failure to acknowledge that the correlation in a dataset was the result of chance. The process of data dredging involves testing multiple hypotheses using a single data set by exhaustively searching, perhaps for combinations of variables that might show a correlation, and perhaps for groups of cases or observations that show differences in their mean or their breakdown by some other variable. Simply defined, it is seeking more information from a data set than it contains. This misuse of data analysis to find patterns in data that can be presented as statistically significant dramatically increases and understates the risk of false positives. This is done by performing many statistical tests on the data and only reporting those that come back with significant results. It is the inverse of cherry-picking. With Cherry Picking you pick the data that is most interesting, and with Data Dredging you pick the most interesting conclusion. While looking for patterns in data is legitimate, applying a statistical test of significance or hypothesis test to the same data until a pattern emerges is prone to abuse. Data dredging undermines the integrity of research by prioritizing statistical significance over substantive validity. Data dredging often arises from a failure to pre-specify hypotheses, lack of transparency in reporting, or excessive reliance on p-values as markers of meaningful findings.</p><p>The types of Data Dredging include; Optional stopping, Post-hoc data replacement, Post-hoc grouping, Hypothesis suggested by non-representative data, Systematic Bias, and Multiple modelling. Optional stopping is a practice where one collects data until some stopping criteria is reached. While it is a valid procedure, it is easily misused. Post-hoc data replacement occurs when data is removed after some data analysis is already done on it, on the pretext of removing outliers, thereby increasing the false positive rate. Post-hoc grouping occurs when a dataset contains multiple features, then one or more of the features can be used as grouping, and potentially create a statistically significant result. The hypothesis suggested by non-representative data occurs when the data itself is taken out of context to be seen as strongly supporting the correlation. Systematic Bias is a systematic error in the analysis that supports the correlation. Multiple modelling is the process of deciding which covariates to include in a relationship explaining one or more other variables, which comes down to the researchers’ bias most often.</p><p><strong>Case Study:</strong> A great case of Data dredging is the XKCD comic titled Significant. In the comic, researchers test whether Jelly bean causes acne. They found no connection between Jelly beans and acne. In the quest to achieve their desired outcome, they went on to test multiple jelly bean colours to determine if they cause acne. After several tests, one colour (green) appears significant after multiple comparisons, even though it was a statistical artefact of random chance. This parodies the risk of conducting numerous tests without accounting for false discovery rates.</p><h3>Publication Bias</h3><p>How interesting a research finding is affects how likely it is to be published, distorting the impression of reality. For every study that shows statistically significant results, there may have been many similar tests that were inconclusive. However, significant results are more interesting to read about and more likely to be published. Not knowing how many boring studies were filed away impacts our ability to judge the validity of the results we read about. When a company claims a certain activity had a major positive impact on growth, other companies may have tried the same thing without success, so they don’t discuss it.</p><p><strong>Case Study:</strong> Research has shown that the pharmaceutical industry often does not publish data from negative studies, particularly in psychiatric literature. This non-publication of negative outcomes can lead to an overestimation of a drug’s efficacy and underreporting of potential risks, impacting clinical decision-making and patient safety (Nassir Ghaemi et al., 2008). A case study published at PubMed highlights how publication bias influences a series of drug education reviews. Initial analyses with positive findings were published and became influential in policy and practice. However, subsequent analyses by the same review team, which demonstrated the earlier findings to be unreliable, were not published. This selective publication led to the continued use of ineffective drug education strategies (McCambridge, 2007).</p><h3>Sampling Bias</h3><p>This is the act of concluding from a set of data that isn’t representative of the population that one is trying to study. It is a bias in which a sample is collected in such a way that some members of the intended population have a lower or higher sampling probability than others. It results in a biased population sample in which all individuals, or instances, were not equally likely to have been selected. This could culminate in results being erroneously attributed to the phenomenon under study rather than to the sampling method.</p><p>Types of Sampling bias include; Symptom-based sampling, Truncate selection bias, and the caveman effect. An instance of Symptom-based sampling is the study of medical conditions which begins with anecdotal reports. By their nature, such reports only include those referred for diagnosis and treatment. A child who can’t function in school is more likely to be diagnosed with dyslexia than a child who struggles but passes. A child examined for one condition is more likely to be tested for and diagnosed with other conditions, skewing comorbidity statistics. Truncate selection bias can occur in pedigree studies when geneticists cannot easily obtain data from human populations. For instance, when investigating a human characteristic to determine if it follows simple Mendelian inheritance if both parents are carriers (non-expressive heterozygotes) and do not show the trait, their children have a 25% chance of exhibiting it. The challenge is that we can only identify carrier families if they have a child who expresses the characteristic, complicating the tracing of inheritance patterns, as noted in Sutton’s textbook. An instance of the caveman effect is that much of our understanding of prehistoric peoples comes from caves, such as cave paintings made nearly 40,000 years ago. If there had been contemporary paintings on trees, animal skins or hillsides, they would have been washed away long ago.</p><p><strong>Case Study:</strong> A scenario where a company bases its entire marketing strategy on feedback from the vocal minority (a small, vocal group of customers) embodies bias sampling. This limited perspective can lead to misunderstandings about what the broader customer base actually wants, a phenomenon known as Biased Sampling (Patov, 2024).</p><h3>Coming Up in Part 3</h3><p>Part 3 moves from what data gets shown to how the data you do have can still mislead you once it is grouped, filtered, or read causally: Survivorship Bias, Simpson’s Paradox, False Causality, and Gerrymandering (the Modifiable Areal Unit Problem).</p><h3>References</h3><p>McCambridge J. (2007). A case study of publication bias in an influential series of reviews of drug education. <em>Drug and alcohol review, 26</em>(5), 463–468. <a href="https://doi.org/10.1080/09595230701494366">https://doi.org/10.1080/09595230701494366</a></p><p>Nassir Ghaemi, S., Shirzadi, A. A., &amp; Filkowski, M. (2008). Publication bias and the pharmaceutical industry: the case of lamotrigine in bipolar disorder. <em>Medscape journal of medicine, 10</em>(9), 211.</p><p>Patov, A. (2024). Biased sampling: Misjudging customer preferences from Incomplete Data. <a href="https://www.renascence.io/journal/biased-sampling-misjudging-customer-preferences-from-incomplete-data?utm">https://www.renascence.io/journal/biased-sampling-misjudging-customer-preferences-from-incomplete-data?utm</a></p><p>She, Z., Ayer, T., &amp; Montanera, D. (2022). Can big data cure risk selection in healthcare capitation program? A game theoretical analysis. <em>Manufacturing &amp; Service Operations Management, 24</em>(6), 3117–3134.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=de78b4550890" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How Statistical Fallacies Mislead Decision-Making: Building a Theoretical and Practical Framework]]></title>
            <link>https://medium.com/@emiklad/how-statistical-fallacies-mislead-decision-making-building-a-theoretical-and-practical-framework-46e27c66f83c?source=rss-7f9d555fe2bf------2</link>
            <guid isPermaLink="false">https://medium.com/p/46e27c66f83c</guid>
            <category><![CDATA[policy]]></category>
            <category><![CDATA[statitics]]></category>
            <category><![CDATA[research]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Emmanuel Nnajiofor]]></dc:creator>
            <pubDate>Mon, 07 Sep 2026 11:28:59 GMT</pubDate>
            <atom:updated>2026-09-07T14:01:24.500Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*nY7PgY9e3KsZEzIE" /><figcaption>Photo by <a href="https://unsplash.com/@kommumikation?utm_source=medium&amp;utm_medium=referral">Mika Baumeister</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>Part 1: Why Do Smart People Trust Bad Numbers?</h3><p>A hospital administrator studies a chart and feels reassured.<br>A policymaker sees a headline statistic, nods and signs off on a new program. In each of these scenarios, the person making the call is not careless, and they are not unintelligent. They are doing exactly what they have been told to do: trust the data. And yet, again and again, smart, well-meaning people end up making bad decisions built on numbers that looked solid but were not. The question worth asking is not whether these people were foolish. It is why numbers that look objective can still lead intelligent people astray.</p><p>This series exists to answer that question, and it starts with the same premise that has driven statistical thinking for over a century.</p><blockquote>Statistical thinking will one day be as necessary for efficient citizenship as the ability to read and write — (Wells, 1903).</blockquote><p>Wells underscores the importance of statistics-based decision-making in not just our everyday lives, but in achieving effective management and operational excellence. Using measurable and objective evidence to make informed decisions and drive improvements highlights the essence of statistics and data, while advocating for scepticism towards decisions made without data. Lord Deming (Statistician, Author, Professor, Consultant, and Lecturer) further underscores this point, asserting that reliance on data is essential and cautions that opinions without data lack credibility. He asserts <em>“In God we trust. All others must bring data”</em> (Deming, 1943) and that <em>“Without data, you’re just another person with an opinion” </em>(Deming, 1943) implying that decisions based on data and Statistical analysis, rather than assumptions, intuition, or anecdotal evidence, help eliminate biases and ensure that strategies are grounded in reality.</p><p>However, in this era of statistics-based decision-making, humans have discovered that even statistics is prone to errors too. In other words, the use of statistics is not without pitfalls. These pitfalls are commonly referred to as fallacies in data-based decision-making. Sometimes, these fallacies are consciously evoked to deceive the unsuspecting audience into engaging in a predetermined thought pattern or drawing an expected conclusion. Other times, the fallacies are sincere errors. Even well-meaning analysts and decision-makers can fall prey to statistical fallacies that lead to flawed conclusions, often with far-reaching consequences.</p><blockquote>“Most people use statistics like a drunk uses lamp-posts — for support rather than illumination” — (Lang, 1910).</blockquote><p>This emphasizes the statistical fallacy of using statistics to shape narratives other than shine light in the dark areas.</p><p>In this seven part series, we will explore common statistical fallacies and propose a theoretical framework for understanding them, while also exploring real-world scenarios. This will expose the need for careful and thorough interpretation of statistical data.</p><p>Beyond this introduction, here’s what the rest of the series covers:</p><p><strong>Part 2: Fallacies of Cherry-Picked and Suppressed Data</strong> Cherry-Picking, Data Dredging, Publication Bias, and Sampling Bias, fallacies rooted in what data gets seen, collected, or reported in the first place.</p><p><strong>Part 3: When the Data You Have Isn’t the Data You Need</strong> Survivorship Bias, Simpson’s Paradox, False Causality, and Gerrymandering (the Modifiable Areal Unit Problem), fallacies that arise from how data is grouped, filtered, or read causally.</p><p><strong>Part 4: Misreading Randomness, Chance, Models, and False Patterns</strong> Gambler’s Fallacy, Regression to the Mean, Overfitting, and the Danger of Summary Metrics, fallacies born from misunderstanding randomness and model complexity.</p><p><strong>Part 5: When Measuring Something Changes It</strong> Cobra Effect, Hawthorne Effect, McNamara Fallacy, and Overgeneralization, fallacies where incentives, observation, and over-reliance on metrics distort behavior and conclusions.</p><p><strong>Part 6: Why We Fall for This, the Theory Behind the Fallacies</strong> The four theoretical foundations tying all sixteen fallacies together: Cognitive Bias Theory, Probability Theory, Causal Inference Theory, and Statistical Methodology Theory.</p><p><strong>Part 7: From Theory to Practice, Fixing Data-Driven Decision-Making</strong> The practical implications of these fallacies for decision-makers, concrete recommendations for avoiding them, and closing thoughts.</p><h3>References</h3><p>Deming, W. E. (1943). <em>Statistical adjustment of data.</em></p><p>Lang, A. (1910). Speech, quoted in Alan L. Mackay’s <em>The Harvest of a Quiet Eye</em> (1977), as reported in <em>Chambers Dictionary of Quotations</em> (2005), p. 488.</p><p>Wells, H.G. (1903). <em>Mankind in the Making.</em> London: Chapman &amp; Hall.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=46e27c66f83c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding the Decision Trees Algorithm: A Guide to Data-Driven Decisions]]></title>
            <link>https://medium.com/@emiklad/understanding-the-decision-trees-algorithm-a-guide-to-data-driven-decisions-78259fc7f581?source=rss-7f9d555fe2bf------2</link>
            <guid isPermaLink="false">https://medium.com/p/78259fc7f581</guid>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[healthtech]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[analytics]]></category>
            <dc:creator><![CDATA[Emmanuel Nnajiofor]]></dc:creator>
            <pubDate>Mon, 28 Oct 2024 09:23:55 GMT</pubDate>
            <atom:updated>2024-10-28T09:23:55.268Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Decision Trees are one of the most intuitive and adaptable algorithms in data science, serving as the backbone of many classification and regression tasks. If you’ve ever wondered how machines can make structured decisions similar to human logic, decision trees are a fundamental part of that answer. From diagnosing health conditions to understanding customer behaviors, they break down complex decision-making into clear, visual steps.</em></p><p><em>Let’s dig into what decision trees are, their structure, their real-world applications, and some of their strengths and weaknesses. I’ll also introduce ensemble methods like Random Forests that overcome some of the tree’s core limitations.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/612/1*EDTF62g32QoRTHOQ2KX-3w.jpeg" /></figure><h3>Table of Content</h3><h4>1. What is a Decision tree</h4><h4>2. Structure of a Decision tree</h4><h4>3. Real-World Applications of Decision Trees</h4><h4>4. Strengths and Weaknesses of Decision Trees</h4><h4>5. Conclusion</h4><h4>6. Credit</h4><h3>What is a Decision tree?</h3><p>In simple terms, a decision tree is an algorithm that breaks down a decision-making process into a series of conditions or “questions.” Think of it as a flowchart where each “yes” or “no” answer branches out to another question, ultimately leading to a decision. This structure makes it easy to visualize and understand how decisions are made.</p><p>The decision tree algorithm performs two main tasks:<br><strong>- Classification</strong>: It sorts data points into categories (e.g., “spam” or “not spam”).<br><strong>- Regression:</strong> It predicts continuous values, such as estimating a house’s price.</p><p>Decision trees are powerful tools in data analytics and machine learning. Not only do they form the basis for more advanced algorithms like Random Forests, but they’re also a go-to for data scientists and analysts looking to understand relationships in their data quickly.</p><h4>The structure of a Decision Tree</h4><p>A decision tree consists of three main components: root nodes, internal nodes, and leaf nodes. Here’s a breakdown of each:</p><p><strong>- Root Node:</strong> The root node represents the starting point of the decision tree and contains the entire dataset. The algorithm selects a feature that best splits the data based on a particular criterion (more on this in the “splitting criteria” section). <br><strong>- Internal Nodes:</strong> These nodes represent decision points and further split the data based on a feature condition. Each internal node contains one incoming edge and multiple outgoing edges, leading to other nodes or outcomes.<br><strong>- Leaf Nodes:</strong> Leaf nodes represent the end of a branch, where a final decision or prediction is made. Each leaf node corresponds to a class label (in classification) or a continuous value (in regression).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*jhKN157vC5e9XF6vvzmR9Q.png" /></figure><h4><strong>How does the algorithm decide splits?</strong></h4><p>The most critical part of building a decision tree is determining how to split nodes. To decide this, decision trees rely on certain splitting criteria:</p><p>1. <strong>Gini Impurity:</strong> Measures the “impurity” of a dataset. A low Gini impurity means the node is mostly one class, while high impurity indicates mixed classes. The goal is to select the feature that most reduces Gini impurity.<br>2. <strong>Entropy and Information Gain:</strong> Entropy measures the uncertainty in a dataset, and information gain quantifies how much entropy decreases when a split is made. Higher information gain is better for achieving clear separations.</p><p>Here’s a practical example: if we’re building a decision tree to decide whether to go surfing, the root node might be the “Outlook” (Sunny, Cloudy, Rainy). If it’s sunny, we may then split on “Humidity” (High, Normal), and based on that, determine our activity (e.g., “Stay Inside” if humidity is high or “Go Swimming” if it’s normal).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/1*pO60Th_6sQcEEC_6IxJ1Sw.png" /></figure><h3>Real-World Applications of Decision Trees</h3><p>Decision trees are powerful in their simplicity, allowing for applications across multiple industries:</p><h4>Healthcare: Predicting patient outcomes and diagnoses</h4><p>In healthcare, decision trees can assist in diagnosing conditions by analyzing patient symptoms and histories. For example, a decision tree might help predict whether a patient with certain symptoms has a specific disease, aiding doctors in making data-driven diagnoses. Genomics is another area where decision trees identify genetic markers for diseases by comparing patients’ genomic data.</p><h4>Finance: Risk assessment and loan approval</h4><p>Banks and financial institutions use decision trees to assess risk in loan approvals. A decision tree might evaluate an applicant’s credit score, income, employment status, and other financial factors to predict the likelihood of loan repayment. Decision trees are also employed in option pricing to analyze potential price movements of financial assets, providing valuable insights into investment decisions.</p><h4>Marketing: Customer churn prediction and segmentation</h4><p>In marketing, decision trees can predict customer churn by analyzing factors like purchase history, engagement, and demographics. Marketers can also use decision trees for customer segmentation, allowing them to create targeted campaigns tailored to specific customer groups.</p><h3>Strengths and Weaknesses of Decision Trees</h3><p>Like any algorithm, decision trees come with advantages and disadvantages.</p><h4><strong>Advantages</strong></h4><h4>1. Interpretability and Explainability</h4><p>Decision trees are highly interpretable, making them an excellent choice when transparency is essential.</p><h4>2. Handling Mixed Data Types</h4><p>Decision trees can handle both numerical and categorical data, making them versatile across various data sources.</p><h4>3. No Requirement for Data Normalization</h4><p>Unlike algorithms that require normalized data, decision trees work effectively without scaling features.</p><h4>Disadvantages</h4><h4>1. Overfitting</h4><p>Decision trees are prone to overfitting, especially when they grow too deep. A large tree can “memorize” the training data, losing generalization. <strong><em>Pruning </em></strong>(removing parts of the tree that do not provide much information) is often used to combat this.</p><h4>2. Instability</h4><p>Small changes in the training data can result in a dramatically different tree structure, making decision trees less reliable in high-variance scenarios.</p><h4>3. High Variance</h4><p>Decision trees tend to have high variance, meaning their predictions can vary significantly with slight changes in the data.</p><p>To address some of these limitations, data scientists often turn to ensemble methods, like Random Forests, which combine multiple decision trees to boost performance and stability.</p><h4>Ensemble Techniques: Overcoming Decision Tree Limitations</h4><p>Ensemble methods combine multiple decision trees to form more robust models. Here’s a look at two popular ensemble methods:</p><p><strong>1. Random Forests</strong><br> Random Forests create an ensemble by training multiple decision trees on random subsets of data and features. Each tree in the forest makes a prediction, and the final output is based on the majority vote (classification) or the average prediction (regression) across all trees. This approach reduces overfitting, provides higher accuracy, and significantly lowers variance compared to a single decision tree.</p><p><strong>- How It Works:</strong> Randomly select samples and features, train a decision tree, and repeat this process to build a “forest” of trees.<br><strong> — Advantages: </strong>Improved accuracy, reduced overfitting, and stability against small changes in data.</p><p><strong>2. Gradient Boosting</strong><br> Unlike Random Forests, which trains multiple independent trees, Gradient Boosting builds trees sequentially. Each new tree attempts to correct the errors of the previous one. By combining weak learners (simple trees), Gradient Boosting creates a strong model capable of capturing complex patterns.</p><p>-<strong> How It Works</strong>: Sequentially add trees that correct residual errors from previous trees, optimizing for better accuracy.<br> — <strong>Advantages:</strong> High predictive accuracy and flexibility in handling different types of data, although it can be computationally intensive.</p><p>Together, these ensemble methods demonstrate how decision trees can serve as the foundation for powerful machine learning models that handle complex tasks while mitigating the weaknesses of individual trees.</p><h3>Conclusion</h3><p>Decision trees are a foundational tool in data science and machine learning, offering a balance of interpretability and predictive power. They’re simple enough for quick analysis and powerful enough to serve as the core of complex ensemble algorithms like Random Forests and Gradient Boosting. By breaking down data into understandable decisions, decision trees provide valuable insights across industries, from healthcare to finance and marketing.</p><p>As you explore decision trees, keep in mind that their simplicity can lead to limitations. Ensemble methods are excellent next steps for enhancing performance, reducing overfitting, and tackling high-variance data, allowing you to apply the logic of decision trees at scale.</p><p>Whether used alone or within an ensemble, decision trees remain a cornerstone of predictive modeling and decision-making, bridging the gap between complex data and actionable insights.</p><p>Stay tuned for my next article if you’re excited to get your hands dirty on how we can harness this algorithm in real-life applications. Let’s get our hands on some coding.</p><h3>Credit</h3><p><a href="https://www.geeksforgeeks.org/decision-tree-introduction-example/">GeekforGeeks</a></p><p><a href="https://www.ibm.com/topics/decision-trees#:~:text=A%20decision%20tree%20is%20a,internal%20nodes%20and%20leaf%20nodes.">IBM</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=78259fc7f581" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A beginner’s guide to react query (Tanstack V5), part 5: using the queryClient.]]></title>
            <link>https://medium.com/@emiklad/a-beginners-guide-to-react-query-tanstack-v5-part-5-using-the-queryclient-fc143166977f?source=rss-7f9d555fe2bf------2</link>
            <guid isPermaLink="false">https://medium.com/p/fc143166977f</guid>
            <category><![CDATA[reactjs]]></category>
            <category><![CDATA[tanstack-query]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[front-end-development]]></category>
            <category><![CDATA[react-query]]></category>
            <dc:creator><![CDATA[Emmanuel Nnajiofor]]></dc:creator>
            <pubDate>Wed, 18 Sep 2024 06:41:54 GMT</pubDate>
            <atom:updated>2024-09-18T06:41:54.095Z</atom:updated>
            <content:encoded><![CDATA[<p>For four episodes, we have discussed about react-query v5. We have seen how much power it gives developers to build applications that scale, with efficient API <a href="https://medium.com/@emiklad1993/a-beginners-guide-to-react-query-tanstack-v5-part-3-the-usequery-hook-af6af5abea07">queries</a> and <a href="https://medium.com/@emiklad1993/a-beginners-guide-to-react-query-tanstack-v5-part-4-the-usemutation-hook-d24312bf952c">mutations</a>. If you have come this far, you’re a superstar and you have all you need to build top-tier production-grade applications. If you’re new here and have no idea what I’m talking about, start <a href="https://medium.com/@emiklad1993/a-beginners-guide-to-react-query-tanstack-query-v5-181eb9c813de">here</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*mPtE1zpZI9IyyRZX" /><figcaption>Photo by <a href="https://unsplash.com/@redaquamedia?utm_source=medium&amp;utm_medium=referral">Denny Müller</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>There is one more utility that we get with react-query. We talked about the query client can be configured <a href="https://medium.com/@emiklad1993/a-beginners-guide-to-react-query-tanstack-v5-part-2-the-query-client-d385d5e092f6">here</a>, now however we would take a look at what is being returned by the query-clientand how we can use it in our application. The query client allows us to interact with a cache.</p><pre>import { QueryClient } from &#39;@tanstack/react-query&#39;<br><br>const {<br>    fetchQuery,<br>    fetchInfiniteQuery,<br>    prefetchQuery,<br>    prefetchInfiniteQuery,<br>    getQueryData,<br>    ensureQueryData,<br>    getQueriesData,<br>    setQueryData,<br>    getQueryState,<br>    setQueriesData,<br>    invalidateQueries,<br>    refetchQueries,<br>    cancelQueries,<br>    removeQueries,<br>    resetQueries,<br>    isFetching,<br>    isMutating,<br>    getDefaultOptions,<br>    setDefaultOptions,<br>    getQueryDefaults,<br>    setQueryDefaults,<br>    getMutationDefaults,<br>    setMutationDefaults,<br>    getQueryCache,<br>    getMutationCache,<br>    clear,<br>    resumePausedMutations<br>} = new QueryClient({<br>  defaultOptions: {},<br>})<br><br></pre><p>Let’s dive into the various methods provided by the QueryClient and how they can be used effectively in your applications. Each of these methods serves a distinct purpose, allowing you to manage queries and their states with precision.</p><p>First up is <strong>fetchQuery</strong>. This method is used when you want to fetch data for a query, either by retrieving it from the cache if it&#39;s already stored or by making a network request if it isn&#39;t. The fetchQuery method is particularly useful when you need to ensure data is available before rendering a component. It accepts three main arguments: queryKey, which uniquely identifies the query; queryFn, the function responsible for fetching the data; and an optional options object for additional configurations. For example, you might use fetchQuery to get a specific todo item by its ID.</p><pre>const data = await fetchQuery([&#39;todos&#39;, todoId], () =&gt; fetchTodoById(todoId));</pre><p>Moving on to <strong>fetchInfiniteQuery</strong>, this method is tailored for fetching paginated data, making it ideal for implementing infinite scrolling. Similarly to fetchQuery, it accepts a queryKey, a queryFn, and options. However, fetchInfiniteQuery is optimized for handling pages of data, allowing you to manage loading additional pages seamlessly as the user scrolls through the content. In the snippet below we fetch a list of posts with pagination.</p><pre>const data = await fetchInfiniteQuery([&#39;posts&#39;], fetchPosts);</pre><p>Next, we have <strong>prefetchQuery</strong>, which is all about preparing data ahead of time. This method allows you to preload data into the cache without triggering a re-render, making it perfect for scenarios where you anticipate needing data soon but don&#39;t want to display it immediately. This is similar to fetchQuery, it takes a queryKey, queryFn, and options.</p><pre>await prefetchQuery([&#39;todos&#39;, todoId], () =&gt; fetchTodoById(todoId));</pre><p><strong>prefetchInfiniteQuery</strong> serves a similar purpose but is designed for infinite queries. It lets you preload paginated data into the cache, which can be a game-changer for improving the user experience in apps with infinite scrolling.</p><pre>await prefetchInfiniteQuery([&#39;posts&#39;], fetchPosts);</pre><p>The <strong>getQueryData</strong> method is straightforward—it&#39;s used to retrieve the cached data for a specific query. If the query doesn&#39;t exist in the cache, it returns undefined. This can be handy when you want to check if data is already available before making any network requests.</p><pre>const cachedData = getQueryData([&#39;todos&#39;, todoId]);</pre><p><strong>ensureQueryData</strong> takes things a step further by ensuring that data for a query is available. If it&#39;s not already cached, it will fetch the data and cache it for future use. This method is particularly useful when you want to guarantee that data is ready, without having to check and fetch it manually.</p><pre>const data = await ensureQueryData([&#39;todos&#39;, todoId], () =&gt; fetchTodoById(todoId));</pre><p>When you need to retrieve data for multiple queries simultaneously, <strong>getQueriesData</strong> comes into play. This method returns an array of results for the specified queries, allowing you to handle multiple data points in one go.</p><pre>const queriesData = getQueriesData([[&#39;todos&#39;, 1], [&#39;todos&#39;, 2]]);</pre><p>On the other hand, <strong>setQueryData</strong> allows you to manually set or update the cached data for a specific query. This is particularly useful for optimistic updates, where you update the UI with an assumed result before confirming it with a network request.</p><pre>setQueryData([&#39;todos&#39;, todoId], { id: todoId, text: &#39;New Todo&#39; });</pre><p><strong>getQueryState</strong> provides insight into the current state of a query, including its status, error, and data. This can be crucial for debugging or for implementing custom logic based on the query&#39;s state.</p><pre>const queryState = getQueryState([&#39;todos&#39;, todoId]);</pre><p>If you need to update the cached data for multiple queries at once, <strong>setQueriesData</strong> is your go-to method. It allows for batch updates, which can be more efficient and cleaner than updating queries one by one.</p><pre>setQueriesData([[&#39;todos&#39;, 1], [&#39;todos&#39;, 2]], (oldData) =&gt; ({<br>  ...oldData,<br>  completed: true,<br>}));</pre><p>To mark queries as stale and trigger a refetch the next time they’re accessed, you can use <strong>invalidateQueries</strong>. This method is useful when you know that data has changed on the server and needs to be refreshed.</p><pre>invalidateQueries([&#39;todos&#39;]);</pre><p><strong>refetchQueries</strong> is used to force a refetch of specific queries, ensuring the data is up-to-date regardless of its current state. We can use this in response to certain user actions within our application.</p><pre>await refetchQueries([&#39;todos&#39;]);</pre><p>Sometimes, you may need to stop queries in progress. This is where <strong>cancelQueries</strong> comes in. It allows you to cancel ongoing queries, preventing them from completing and potentially saving unnecessary network traffic.</p><pre>cancelQueries([&#39;todos&#39;]);</pre><p>When it’s time to clean up, <strong>removeQueries</strong> can be used to remove specific queries from the cache entirely. This helps clear out old or unnecessary data that you no longer need.</p><pre>removeQueries([&#39;todos&#39;]);</pre><p>If you need to reset the state of certain queries back to their initial state, <strong>resetQueries</strong> does just that. It clears errors, data, and sets the query back to its original form.</p><pre>resetQueries([&#39;todos&#39;]);<br><br>or<br><br>resetQueries({ queryKey, exact: true })</pre><p>To check if any queries are currently in the process of fetching data, you can use <strong>isFetching</strong>.</p><pre>// single query<br>const fetching = isFetching({ queryKey: [&#39;todos&#39;] });<br><br>or<br><br>//all queries<br>if (isFetching()) {<br>  console.log(&#39;At least one query is fetching!&#39;)<br>}</pre><p>Similarly, <strong>isMutating</strong> checks if any mutations are currently in progress.</p><pre>// Get the number of all fetching mutations<br>await isMutating()<br><br>// Filter mutations by mutationKey<br>await isMutating({ mutationKey: [&#39;todo&#39;] })<br><br>// Filter mutations using a predicate function<br>await isMutating({<br>  predicate: (mutation) =&gt; mutation.options.variables?.id === 1,<br>})<br><br>if (queryClient.isMutating()) {<br>  console.log(&#39;At least one mutation is fetching!&#39;)<br>}</pre><p>When you need to retrieve or set the default options for all queries and mutations in the client, you can use <strong>getDefaultOptions</strong> and <strong>setDefaultOptions</strong>. These methods give you control over the baseline behavior of queries and mutations. This is unlikely because you have already configured these options globally. But it’s available if you need to use it.</p><pre>const defaultOptions = getDefaultOptions();<br>setDefaultOptions({<br>  queries: {<br>    refetchOnWindowFocus: false,<br>  },<br>});</pre><p>For finer control over individual query or mutation types, <strong>getQueryDefaults</strong> and <strong>setQueryDefaults</strong> allow you to get and set default configurations for specific queries. This is useful when you have certain types of queries that need to behave differently from the global settings.</p><pre>const queryDefaults = getQueryDefaults([&#39;todos&#39;]);<br>setQueryDefaults([&#39;todos&#39;], { staleTime: 10000 });</pre><p>Similarly, <strong>getMutationDefaults</strong> and <strong>setMutationDefaults</strong> let you handle default configurations for mutations. These methods are great for standardizing the behavior of your mutations.</p><pre>const mutationDefaults = getMutationDefaults([&#39;addTodo&#39;]);<br>setMutationDefaults([&#39;addTodo&#39;], { onSuccess: () =&gt; console.log(&#39;Todo added!&#39;) });</pre><p>To access the internal cache of all queries or mutations, <strong>getQueryCache</strong> and <strong>getMutationCache</strong> are available. These methods allow you to directly manipulate or inspect the cache, which can be useful for advanced scenarios.</p><pre>const queryCache = getQueryCache();<br>const mutationCache = getMutationCache();</pre><p>If you have mutations that were paused due to network issues or other interruptions, <strong>resumePausedMutations</strong> can be used to resume them, ensuring that they complete as intended.</p><pre>resumePausedMutations();</pre><p>Finally, <strong>clear</strong> offers a way to reset the entire query and mutation cache, effectively resetting the client&#39;s stored state. This can be useful during testing or when you want to ensure a clean state.</p><pre>clear();</pre><p>If you’ve come this far, you should be a ninja at making queries and mutations now, you have all you need to manage and scale API handling within your application.</p><p>This brings us to the end of this series. I’ll be looking forward to your comments.</p><p>Also, please drop a clap (or two).</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fc143166977f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A beginner’s guide to react query (Tanstack V5), part 4: The useMutation hook.]]></title>
            <link>https://medium.com/@emiklad/a-beginners-guide-to-react-query-tanstack-v5-part-4-the-usemutation-hook-d24312bf952c?source=rss-7f9d555fe2bf------2</link>
            <guid isPermaLink="false">https://medium.com/p/d24312bf952c</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[reactjs]]></category>
            <category><![CDATA[react-query]]></category>
            <dc:creator><![CDATA[Emmanuel Nnajiofor]]></dc:creator>
            <pubDate>Tue, 06 Aug 2024 11:19:16 GMT</pubDate>
            <atom:updated>2024-08-06T11:19:16.539Z</atom:updated>
            <content:encoded><![CDATA[<p>The useMutation hook is technically the opposite of the useQuery hook discussed <a href="https://medium.com/@emiklad1993/a-beginners-guide-to-react-query-tanstack-v5-part-3-the-usequery-hook-af6af5abea07">earlier</a> in this series. If you haven’t been following the series, we started with an <a href="https://medium.com/@emiklad1993/a-beginners-guide-to-react-query-tanstack-query-v5-181eb9c813de">introduction</a> to react-query and the <a href="https://medium.com/@emiklad1993/a-beginners-guide-to-react-query-tanstack-v5-part-2-the-query-client-d385d5e092f6">query client</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*cn8lsllOlpWrkygN" /><figcaption>Photo by <a href="https://unsplash.com/@scw1217?utm_source=medium&amp;utm_medium=referral">Suzanne D. Williams</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>useMutation as suggested by the name, handles API interactions within our application that typically mutate data; POST, PUT, PATCH and DEL requests fall into this category.</p><p>As we advance, we will show how this hook paired with <a href="https://axios-http.com/docs/intro">Axios</a> can be used to handle API calls in our application and listen on isPending , isSuccess , isError and isIdle states of our mutations.</p><p>This is what a basic setup for this hook would look like.</p><pre>const {...} = useMutation({<br>  mutationFn,<br>  onError,<br>  onSuccess,<br>  onMutate,<br>  onSettled,<br>  retry,<br>  retryDelay<br>})</pre><p>Now, let’s get into these values and discuss their use case.</p><p>mutationFn : Required function that performs an asynchronous task and returns a promise. The mutation function can receive an argument.</p><pre>const {...} = useMutation({<br>  mutationFn: (args: TArgs) =&gt; Promise&lt;TData&gt;<br>  ...<br>})</pre><p>Now, unlike the useQuery hook which has lost all of its callbacks in the object, the react-query team did not take them out in this new version for the useMutation hook,</p><p>onError and onSuccess are very straightforward as the names imply. Either of these callbacks would run depending on the outcome of the mutation.</p><p>In case of an error, we would have access to the error: TError and in case of success, we would have access to the data: TData within the function, which allows us to tailor the behavior or state of our application.</p><p>In both scenarios, if either returns a promise, it will be awaited and resolved before proceeding.</p><pre>const {...} = useMutation({<br>  onError: (error: TError) =&gt; Promise&lt;unknown&gt; | unknown,<br>  onSuccess: (data: TData) =&gt; Promise&lt;unknown&gt; | unknown,<br>  ...<br>})</pre><p>If you ever need to perform optimistic updates to a resource in hopes that the mutation succeeds;</p><p>onMutate : is an optional callback that allows us to do this. This function will fire before the mutation function is fired and is passed the same variables the mutation function would receive. The value returned from this function will be passed to both the onError and onSettled functions in the event of a mutation failure and can be useful for rolling back optimistic updates.</p><p>onSettled : whenever we need to carry out any operations regardless of the outcome of our mutation, we can use this callback. It allows us to fire a function when the mutation is either successful or encounters an error and receives either the data or error.</p><pre>const {...} = useMutation({<br>  onSettled: (data: TData, error: TError) =&gt; Promise&lt;unknown&gt; | unknown<br>  onMutate: (variables: TVariables) =&gt; Promise&lt;TContext | void&gt; | TContext | void<br>  ...<br>})</pre><p>Outside the callbacks, the useMutation hook allows us to describe how and when our mutations should be retried. This is especially useful when we need to run some sort of background mutation that does not directly get triggered based on user actions. We can make the mutation retry on its own or trigger a retry based on specific errors or disable retries after a number of retries or failureCounts</p><p>All of this can be achieved with retry and retryDelay . The delay parameter lets us specify a delay time before the next retry in milliseconds</p><pre>const {...} = useMutation({<br>  retry: boolean | number | (failureCount: number, error: TError) =&gt; boolean,<br>  retryDelay: number | (retryAttempt: number, error: TError) =&gt; number<br>})</pre><p>Below is a demo setup of what all of this may look like if used together</p><pre>import React from &#39;react&#39;;<br>import { useMutation, useQueryClient } from &#39;react-query&#39;;<br>import axios from &#39;axios&#39;;<br><br>const createPost = async (newPost) =&gt; {<br>  const response = await axios.post(&#39;https://jsonplaceholder.typicode.com/posts&#39;, newPost);<br>  return response.data;<br>};<br><br>const MyComponent = () =&gt; {<br>  const queryClient = useQueryClient();<br><br>  const {...} = useMutation({<br>    mutationFn: createPost,<br>    onError: (error) =&gt; {<br>      console.error(&#39;Error:&#39;, error);<br>    },<br>    onSuccess: (data) =&gt; {<br>      console.log(&#39;Success:&#39;, data);<br>      queryClient.invalidateQueries(&#39;posts&#39;);<br>    },<br>    onMutate: async (newPost) =&gt; {<br>      await queryClient.cancelQueries(&#39;posts&#39;);<br><br>      const previousPosts = queryClient.getQueryData(&#39;posts&#39;);<br><br>      queryClient.setQueryData(&#39;posts&#39;, (old) =&gt; [...old, { ...newPost, id: Date.now() }]);<br><br>      return { previousPosts };<br>    },<br>    onSettled: (data, error) =&gt; {<br>      if(data){<br>      //do something <br>      }<br>      if(error){<br>      //do something if error<br>      }<br>      queryClient.invalidateQueries(&#39;posts&#39;);<br>    },<br>    retry: (failureCount, error) =&gt; {<br>      if (error.response?.status === 404) {<br>        // Do not retry if the error status is 404<br>        return false;<br>      }<br>      // Retry up to 3 times for other errors<br>      return failureCount &lt; 3;<br>    },<br>    retryDelay: (failureCount, error) =&gt; {<br>      if (error.response?.status === 500) {<br>        // For 500 errors, use a fixed delay<br>        return 1000;<br>      }<br>      // Exponential backoff for other errors<br>      return Math.min(1000 * 2 ** failureCount, 30000);<br>    },<br>  });<br><br><br>  return (<br>    &lt;div&gt;<br>     // ...<br>    &lt;/div&gt;<br>  );<br>};<br><br>export default MyComponent;</pre><p>So far we have seen what we need to configure the useMutation hook, now we would consider the values within the object returned.</p><pre>const {<br>  data,<br>  error,<br>  isError,<br>  isPending,<br>  isSuccess,<br>  status,<br>  failureCount,<br>  isIdle,<br>  mutate,<br>  mutateAsync,<br>  reset,<br>} = useMutation({<br>    ...<br>})</pre><p>In our previous post <a href="https://medium.com/@emiklad1993/a-beginners-guide-to-react-query-tanstack-v5-part-3-the-usequery-hook-af6af5abea07">here</a>, we already discussed data, error, isError, isPending, isSuccess and status . The other values are unique to mutations.</p><blockquote>If you have come across older versions of this hook, you would notice that the isLoading value has been removed from this object and replaced with isPending</blockquote><p>failureCount : This property indicates the number of times the mutation has failed. It’s useful for implementing custom retry logic, as you can determine how many attempts have been made and decide whether to continue retrying or not.</p><p>isIdle : This boolean property indicates whether the mutation has not been triggered yet. This can be used for conditional rendering or logic based on whether the mutation has been executed.</p><p>mutate : This is the function we use to trigger our mutations, It receives the variables/arguments required for the mutation and an optional configuration object to override the default behavior for that specific call.</p><pre>mutate(variables, {<br>  onError,<br>  onSettled,<br>  onSuccess,<br>})</pre><p>mutateAsync : Similar to mutate, this function also triggers the mutation but returns a promise. This is useful when we need to handle the mutation result using async-await syntax.</p><p>reset : This function cleans the mutation&#39;s internal state. It’s useful for clearing error or success states and resetting the mutation to its initial state.</p><p>All of this can be put together in our component like so;</p><pre>import React from &#39;react&#39;;<br>import { useMutation, useQueryClient } from &#39;react-query&#39;;<br>import axios from &#39;axios&#39;;<br><br>const createPost = async (newPost) =&gt; {<br>  const response = await axios.post(&#39;https://jsonplaceholder.typicode.com/posts&#39;, newPost);<br>  return response.data;<br>};<br><br>const MyComponent = () =&gt; {<br>  const queryClient = useQueryClient();<br><br>  const {<br>    data,<br>    error,<br>    isError,<br>    isPending,<br>    isSuccess,<br>    status,<br>    failureCount,<br>    isIdle,<br>    mutate,<br>    mutateAsync,<br>    reset,<br>  } = useMutation({<br>    mutationFn: createPost,<br>    onError: (error, variables, context) =&gt; {<br>      console.error(&#39;Error:&#39;, error);<br>      console.log(&#39;Failed post data:&#39;, variables);<br>      console.log(&#39;Previous post data:&#39;, context.previousPosts);<br>    },<br>    onSuccess: (data, variables, context) =&gt; {<br>      console.log(&#39;Success:&#39;, data);<br>      queryClient.invalidateQueries(&#39;posts&#39;);<br>    },<br>    onMutate: async (newPost) =&gt; {<br>      await queryClient.cancelQueries(&#39;posts&#39;);<br><br>      const previousPosts = queryClient.getQueryData(&#39;posts&#39;);<br><br>      queryClient.setQueryData(&#39;posts&#39;, (old) =&gt; [...old, { ...newPost, id: Date.now() }]);<br><br>      return { previousPosts };<br>    },<br>    onSettled: (data, error, variables, context) =&gt; {<br>      queryClient.invalidateQueries(&#39;posts&#39;);<br>    },<br>    retry: (failureCount, error) =&gt; {<br>      if (error.response?.status === 404) {<br>        return false;<br>      }<br>      return failureCount &lt; 3;<br>    },<br>    retryDelay: (failureCount) =&gt; Math.min(1000 * 2 ** failureCount, 30000),<br>  });<br><br>  const handleAddPost = async () =&gt; {<br>    try {<br>      const result = await mutateAsync({ title: &#39;New Post&#39;, body: &#39;This is the content of the new post.&#39; });<br>      console.log(&#39;Post added:&#39;, result);<br>    } catch (error) {<br>      console.error(&#39;Error adding post:&#39;, error);<br>    }<br>  };<br><br>  return (<br>    &lt;div&gt;<br>      &lt;button onClick={handleAddPost} disabled={isPending}&gt;<br>        {isPending ? &#39;Adding...&#39; : &#39;Add Post&#39;}<br>      &lt;/button&gt;<br>      &lt;button onClick={reset} disabled={isIdle}&gt;<br>        Reset<br>      &lt;/button&gt;<br><br>      {isError &amp;&amp; &lt;div&gt;Error: {error.message}&lt;/div&gt;}<br>      {isSuccess &amp;&amp; &lt;div&gt;Post added successfully: {JSON.stringify(data)}&lt;/div&gt;}<br>      &lt;div&gt;Status: {status}&lt;/div&gt;<br>      &lt;div&gt;Failure Count: {failureCount}&lt;/div&gt;<br>    &lt;/div&gt;<br>  );<br>};<br><br>export default MyComponent;</pre><p>The snippet above shows in detail how we can use the values returned by our mutation and how we can configure it.</p><p>In the above snippet, you may notice the usage of the queryClient which we had discussed earlier on <a href="https://medium.com/@emiklad1993/a-beginners-guide-to-react-query-tanstack-v5-part-2-the-query-client-d385d5e092f6">here</a>. But you would also see that we have used it in a slightly different manner. Here we are accessing the values on the client itself. This allows us to do a number of things within our application.</p><p>The next episode on this series would be discussing those values and how we can use them.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d24312bf952c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A beginner’s guide to react query (Tanstack V5), part 3: The useQuery hook.]]></title>
            <link>https://medium.com/@emiklad/a-beginners-guide-to-react-query-tanstack-v5-part-3-the-usequery-hook-af6af5abea07?source=rss-7f9d555fe2bf------2</link>
            <guid isPermaLink="false">https://medium.com/p/af6af5abea07</guid>
            <category><![CDATA[react-query]]></category>
            <category><![CDATA[reactjs]]></category>
            <category><![CDATA[react-query-v3]]></category>
            <dc:creator><![CDATA[Emmanuel Nnajiofor]]></dc:creator>
            <pubDate>Mon, 29 Jul 2024 09:34:26 GMT</pubDate>
            <atom:updated>2024-07-29T09:34:26.989Z</atom:updated>
            <content:encoded><![CDATA[<p>This series has been a walkthrough of the different components and usages of react-query. For the earlier parts, we have discussed in detail the core building blocks and setup for <a href="https://medium.com/@emiklad1993/a-beginners-guide-to-react-query-tanstack-query-v5-181eb9c813de">react-query</a> and the <a href="https://medium.com/@emiklad1993/a-beginners-guide-to-react-query-tanstack-v5-part-2-the-query-client-d385d5e092f6">query client</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*a-WtvoT1c0xPDDVY" /><figcaption>Photo by <a href="https://unsplash.com/@ptrikutam?utm_source=medium&amp;utm_medium=referral">Pavan Trikutam</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>In this episode, we will be taking a deep dive into the useQuery hook and how we can use this alongside <a href="https://axios-http.com/docs/intro">Axios</a> to handle API calls in our application.</p><p>This is the hook provided by react-query that typically handles Get requests to an API endpoint, allowing us to listen on asynchronous events such as isLoading , isSuccess , isError , isFetching .</p><p>The useQuery hook is configured with an object that receives certain parameters describing the exact query function and the behavior of the query.</p><p>Let’s take a moment to look at some of the values of this object.</p><pre>const {...} = useQuery({<br>  queryKey,<br>  queryFn,<br>  enabled,<br>  select<br>})</pre><p>If you read my previous article on the earlier version of this, you will notice that a few things seem to be missing here. This is because commonly used callback events like onError , onSuccess and onSettled have been removed in this version. Curious enough to read a detailed post about why they did this?. <a href="https://tkdodo.eu/blog/breaking-react-querys-api-on-purpose">Check it out here</a>.</p><p>While the names of most of these options are self-explanatory, let’s discuss them however.</p><p>queryKey : A unique identifier for the query. Query keys must be an array at the top level. They can range from a single string in an array to a complex array containing multiple strings and nested objects. As long as the query key is serializable and unique to the query’s data, it is valid to use.</p><pre>useQuery({ queryKey: [&#39;todos&#39;] })</pre><p>The querykey can receive a simple array of strings like this but may also include variables like those below</p><pre>useQuery({ queryKey: [&#39;todos&#39;, page, status] })</pre><p>In scenarios where our queryFunction which we would see shortly receives an argument, we need to add that argument as part of the items in our query key. This is because query keys act as dependencies for query functions, adding dependent variables to the query key will ensure that queries are cached independently and that any time a variable changes, queries will be refetched automatically.</p><pre>const result = useQuery({<br>  queryKey: [&#39;todos&#39;, todoId],<br>  queryFn: () =&gt; fetchTodoById(todoId),<br>})<br></pre><p>queryFn<strong> </strong>: A required function that handles the request. The function must return a promise that resolves data or throws an error. The data cannot be undefined .</p><pre>//A sample request with axios<br>const fetchData = async () =&gt; {<br>  const response = await axios.get(&#39;/api/data-endpoint&#39;);<br>  if (!response.data) {<br>    throw new Error(&#39;Data is undefined&#39;);<br>  }<br>  return response.data;<br>};<br><br>const MyComponent = () =&gt; {<br>  const {...} = useQuery({<br>    queryKey: [&#39;dataKey&#39;],<br>    queryFn: fetchData,<br>  });<br><br>  if (isLoading) return &lt;div&gt;Loading...&lt;/div&gt;;<br>  if (error) return &lt;div&gt;Error: {error.message}&lt;/div&gt;;<br><br>  return (<br>    &lt;&gt;<br>     //render data within component here.<br>    &lt;/&gt;<br>  );<br>};</pre><p>In the above snippet, we use Axios to make a demo request and pass the function as the value for our queryFn callback in the useQuery hook.</p><p>enabled : The enabled parameter is a boolean that allows us to disable the query from automatically running.</p><pre>const MyComponent = ({ todoId }) =&gt; {<br>  const {...} = useQuery({<br>    queryKey: [&#39;todos&#39;, todoId],<br>    queryFn: () =&gt; fetchTodoById(todoId),<br>    enabled: !!todoId<br>  });<br><br>  ...<br>};</pre><p>In the above snippet, we disable the query from running automatically by using the !! syntax to make the todoId act as a boolean value.</p><p>select : This option allows you to transform or select a portion of the data returned by the query function. It modifies the data that is returned but does not change what is stored in the query cache.</p><pre>const MyComponent = ({ todoId }) =&gt; {<br>  const {...} = useQuery({<br>    queryKey: [&#39;todos&#39;, todoId],<br>    queryFn: () =&gt; fetchTodoById(todoId),<br>    selecte: (data: TData) =&gt; {todos: data.items, count: data.items.length}<br>    enabled: !!todoId<br>  });<br><br>  ...<br>};</pre><p>All other parameters on the object like refetchIntervalInBackground ,refetchOnMount, refetchOnReconnect, refetchOnWindowFocus, retry, retryOnMount, retryDelay and refetchInterval that are usually configured on the queryClient and were discussed <a href="https://medium.com/@emiklad1993/a-beginners-guide-to-react-query-tanstack-v5-part-2-the-query-client-d385d5e092f6">here</a>, can also be configured here as well for individual queries. This allows us fine-tune the behaviour of a unique query.</p><p>So far we have discussed the values of the object received by the useQuery hook. Now, we will talk about a second argument that was introduced in this version (V5).</p><pre>const { ... } = useQuery({<br>    ...<br>  },<br>  queryClient,<br>)</pre><p>The useQuery hook now accepts an optional unique queryClient different from the one in the nearest context. This can be useful if we need to define a set of configurations for a group of queries that we want to behave in a particular way.</p><p>At this point, we understand all we need to configure the useQuery hook and fine-tune our queries to get the exact behaviour that we want.</p><p>The hook returns an object containing the data from the query and other information including the different states of the query, errors, and callbacks.</p><pre>const {<br>  data,<br>  error,<br>  isError,<br>  isFetching,<br>  isLoading,<br>  isRefetching,<br>  isPending,<br>  isStale,<br>  isSuccess,<br>  refetch,<br>  status,<br>} = useQuery({...})</pre><p>data : The data returned from the query. If the query is still loading or has failed, this will be undefined until the query is successful. This is the value that allows us access fetched data.</p><p>error : The error object returned from the query if it fails. Can be used to display error messages or handle query failures.</p><p>refetch : The hook returns this value that allows us manually refetch the query. Useful for refreshing data in response to user actions or other events.</p><p>status : The current status of the query. Can be loading, error, or success. This is helpful in controlling UI states and flow based on the overall query status.</p><p>The status of the query can also be checked via booleans returned by the hook. isError , isSuccess , isLoading , isFetching , isRefetchingand isPending</p><p>isStale : Indicates whether the query data is considered stale. We can use this to trigger a refetch.</p><p>A variation of the useQuery Hook exists as useSuspenseQuery .</p><p>It is slightly different from useQuery except that it does not receive the error prop and in the returned object ; data is guaranteed to be defined and status is always success.</p><p>Now that we have covered the useQuery hook, you have all that you would need to use this tool within your react app to handle API-requests efficiently.</p><p>In the next part, we’ll be looking at how to make POST, PUT, DEL, and PATCH requests with mutations via the useMutation hook. See you on the next one.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=af6af5abea07" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A beginner's guide to react query (Tanstack V5), part 2: The query client.]]></title>
            <link>https://medium.com/@emiklad/a-beginners-guide-to-react-query-tanstack-v5-part-2-the-query-client-d385d5e092f6?source=rss-7f9d555fe2bf------2</link>
            <guid isPermaLink="false">https://medium.com/p/d385d5e092f6</guid>
            <category><![CDATA[reactjs]]></category>
            <category><![CDATA[frontend]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[react-query]]></category>
            <category><![CDATA[web-development]]></category>
            <dc:creator><![CDATA[Emmanuel Nnajiofor]]></dc:creator>
            <pubDate>Mon, 15 Apr 2024 09:41:33 GMT</pubDate>
            <atom:updated>2024-04-15T09:41:33.224Z</atom:updated>
            <content:encoded><![CDATA[<p>Hi there, this post is part of a series on react-query. The aim is to help us understand ReactQuery in detail. Feeling lost? — <a href="https://medium.com/@emiklad1993/a-beginners-guide-to-react-query-tanstack-query-v5-181eb9c813de">you can start here</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*yr2uWfgNrSMVnsBk" /><figcaption>Photo by <a href="https://unsplash.com/@joshredd?utm_source=medium&amp;utm_medium=referral">Josh Redd</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>In this post, we would be taking a closer look at the QueyClient . The QueryClient is a central component in React Query that manages caching, fetching, and updating data. It acts as a global store for query results and provides various options that help us describe how we want our queries and mutations to behave.</p><p>In our last post, we looked at three of these options; retry , staleTime and refetchOnWindowFocus</p><pre>const queryClient = new QueryClient({<br>  defaultOptions: {<br>    queries: {<br>      retry: 1,<br>      staleTime: 30000, <br>      refetchOnWindowFocus: false,<br>    },<br>    mutations: {<br>      //...<br>    }<br>  },<br>});</pre><p>Beyond these three, we would be discussing other options provided within the queries and mutations object.</p><pre>const queryClient = new QueryClient({<br>  defaultOptions: {<br>    queries: {<br>      retry: 2,<br>      staleTime: 5000, // 5 seconds<br>      refetchOnMount: true,<br>      refetchOnWindowFocus: true,<br>      refetchOnReconnect: true,<br>      refetchInterval: 5000, //5 seconds<br>      refetchIntervalInBackground: false,<br>    },<br>    mutations: {<br>      retry: 2,<br>    },<br>  },<br>});</pre><h4>Queries</h4><p>Contains settings for how we want our queries to behave whenever we use useQuery in our application.</p><p>retry — This option specifies the number of attempts a query will automatically make in case of a prior failed attempt. In this example, queries will retry up to 2 times. This option can also take boolean values or a fucntion that returns a boolean. If the boolean is false the query would not make another attempt after failure. In the case where the value is true it would continue to make infinite retries until it gets a successful response.</p><p>With a function, we are able to access values like the failureCount and error. These gives use more flexibility, as we can decide what to do with those values in different situations</p><pre>const queryClient = new QueryClient({<br>  defaultOptions: {<br>    queries: {<br>      retry: (failureCount, error) =&gt; {<br>           //...do something with passed argument<br>        },<br>      // ...<br>    },<br>    // ...<br>  },<br>});</pre><p>In this case, queries would be retried until the function return false.</p><p>staleTime — Sets the time in milliseconds after which the cached data is considered stale. Think of staleTime as setting an expiration date for our cached data. When data becomes stale, it means it might not be the most up-to-date version. This option tells React Query how long it can trust the data in its cache before considering it old and needing a refresh.</p><p>Say we set staleTime: 5000. This means our cached data is considered fresh for 5000 milliseconds (or 5 seconds). During this time, React Query will happily serve up this data to our app without bothering the server. But once those 5 seconds are up, it&#39;ll start thinking, &quot;Hmm, maybe it&#39;s time to check if there&#39;s fresher data available.&quot; and it’ll make a query for new data.</p><p>refetchOnMount — This option is like a welcoming committee, ensuring our app greets its users with the freshest data as soon as they arrive. Controls whether a query should be automatically refetched when the component mounts.</p><p>Setting refetchOnMount: true means React Query will kick off a fresh data fetch every time a component is mounted. This ensures that whenever our users land on a page or view, they&#39;re met with the most up-to-date information available.</p><p>refetchOnWindowFocus — Specifies whether a query should be refetched when the window or tab gains focus. Setting it to true ensures that the query is refetched whenever the focus returns to the window or tab. Setting it as false, disables automatic refetching on window focus, meaning data won&#39;t be refreshed when users return to the app window.</p><p>refetchOnReconnect — Picture this scenario: a user’s internet connection drops, then reconnects. They expect the app to update with fresh data, right? That’s precisely what refetchOnReconnect handles. It triggers a data refresh whenever the app reconnects to the internet after a connection loss.Setting this option as true ensures that whenever our users regain connectivity, they’re presented with the most recent data available.</p><p>refetchInterval — We want our app to automatically fetch fresh data at regular intervals, ensuring users always have the latest information.</p><p>It can receive a number or boolean value. Setting a numeric value in milliseconds specifies the time interval between data refetches. For example, refetchInterval: 5000 would trigger a data refresh every 5 seconds. Setting it to true enables automatic data refetching at the default interval specified by React Query.</p><p>refetchIntervalInBackground — Keeps data fresh behind the scenes. This option acts as a silent caretaker, quietly ensuring our app’s data stays fresh even when it’s not in the spotlight. In scenarios where users may switch between apps or leave our app running in the background, refetchIntervalInBackground ensures that data remains fresh and relevant.</p><p>It can receive a number or boolean value. Setting a numeric value specifies the time interval between data refetches, even when the app is in the background. For instance, refetchIntervalInBackground: 60000 would trigger a data refresh every 60 seconds.</p><p>Setting true enables automatic data refetching at the default interval specified by React Query, even when the app is in the background.</p><h4>Mutations</h4><p>The mutations object offers a range of options to customize the behavior of mutation operations. By utilizing these options in the mutations object of our QueryClient setup, we can customize the behavior of mutation operations to suit our specific application requirements. Whether it’s handling errors gracefully, updating UI components, or performing cleanup tasks, React Query provides the flexibility we need to create robust and responsive applications. Let’s take a closer look at some of the options</p><pre>const queryClient = new QueryClient({<br>  defaultOptions: {<br>    queries: {<br>     //...<br>    },<br>    mutations: {<br>      retry: 2,<br>      retryDelay: (attemptIndex) =&gt; attemptIndex * 1000, // Increase delay with each retry<br>      onMutate: async (variables) =&gt; {<br>          // Perform tasks before mutation operation<br>        },<br>      onError: (error, variables, context) =&gt; {<br>          // Handle errors gracefully<br>        },<br>     onSuccess: (data, variables, context) =&gt; {<br>          // Update UI components after successful mutation<br>        },<br>     onSettled: (data, error, variables, context) =&gt; {<br>          // Perform cleanup tasks after mutation operation<br>        },<br>    },<br>  },<br>});</pre><p>retry — Similar to its counterpart in queries, the retry option for mutations specifies the number of attempts a mutation will automatically make in case of a prior failed attempt. This ensures that our app can recover from transient failures, such as network errors.</p><p>retryDelay — The retryDelay option complements retry by specifying the delay (in milliseconds) between retry attempts. This can be particularly useful for mitigating issues such as rate limiting or server congestion.</p><p>onMutate — This option allows us to specify a function to run before the mutation operation begins. It’s useful for tasks like updating local state or performing optimistic updates.</p><p>onError — This option allows us to specify a function to run before the mutation operation begins. It’s useful for tasks like updating local state or performing optimistic updates.</p><p>onSuccess — onSuccess allows us to specify a function to run after the mutation operation succeeds. This can include updating UI components or triggering other actions.</p><p>onSettled — The onSettled option lets us define a function to run after the mutation operation completes, whether it succeeds or fails. It’s useful for performing cleanup tasks.</p><p>Putting it all together</p><pre>const queryClient = new QueryClient({<br>  defaultOptions: {<br>    queries: {<br>      retry: 2,<br>      staleTime: 5000, // 5 seconds<br>      refetchOnMount: true,<br>      refetchOnWindowFocus: true,<br>      refetchOnReconnect: true,<br>      refetchInterval: 5000, //5 seconds<br>      refetchIntervalInBackground: false,<br>    },<br>    mutations: {<br>      retry: 2,<br>      retryDelay: (attemptIndex) =&gt; attemptIndex * 1000, // Increase delay with each retry<br>      onMutate: async (variables) =&gt; {<br>          // Perform tasks before mutation operation<br>        },<br>      onError: (error, variables, context) =&gt; {<br>          // Handle errors gracefully<br>        },<br>       onSuccess: (data, variables, context) =&gt; {<br>          // Update UI components after successful mutation<br>        },<br>       onSettled: (data, error, variables, context) =&gt; {<br>          // Perform cleanup tasks after mutation operation<br>        },<br>    },<br>  },<br>});</pre><p>With this setup, our React Query-powered application is equipped to handle a variety of scenarios with finesse. From keeping data fresh and responsive to gracefully managing mutation operations, React Query’s QueryClient options offer the flexibility and control we need to deliver exceptional user experiences.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d385d5e092f6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A beginners guide to React-query (Tanstack query v5)]]></title>
            <link>https://medium.com/@emiklad/a-beginners-guide-to-react-query-tanstack-query-v5-181eb9c813de?source=rss-7f9d555fe2bf------2</link>
            <guid isPermaLink="false">https://medium.com/p/181eb9c813de</guid>
            <category><![CDATA[reactjs]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[react-query]]></category>
            <category><![CDATA[front-end-development]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Emmanuel Nnajiofor]]></dc:creator>
            <pubDate>Mon, 08 Apr 2024 09:49:34 GMT</pubDate>
            <atom:updated>2024-04-08T09:49:34.175Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*kZyXNBFrgrq6algU" /><figcaption>Photo by <a href="https://unsplash.com/@paulina_milde_jachowska?utm_source=medium&amp;utm_medium=referral">Paulina Milde-Jachowska</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>A while ago I wrote a series on react-query. Now, I’m deciding to put together another one because, as with all things in tech, a lot has changed. In this new series, I would do my best to guide an absolute beginner through the amazing tool from novice to a point where you’re hopefully comfortable working with react-query. I will provide insights into its core principles, practical use cases, and essential components.</p><p>In the world of front-end development, managing asynchronous data fetching, caching, and synchronization can often be a challenging task. React Query emerges as a powerful tool to streamline these processes, making data management in React applications more efficient and intuitive.</p><p>React Query is a library that simplifies data fetching and management in React applications. It offers a declarative approach to handle asynchronous operations, such as fetching data from APIs, caching responses, and managing loading states, all in a clean and efficient manner. Unlike traditional state management libraries, React Query focuses on managing asynchronous server-side data, providing a specialized solution for this specific aspect of application development. It is not a replacement for global store libraries like Zustand or Redux-toolkit, as it aims to handle state on the server-side.</p><p>Personally, react-query is my go-to tool for API integrations whenever I start a project, when you think about it, what’s not to love?<br>It comes with built-in features that make for a simplified and easy-to-manage means to integrate APIs on the frontend.</p><ol><li>Declarative Data Fetching: React Query allows developers to fetch data declaratively using hooks like useQuery. By abstracting away the complexities of imperative data fetching, developers can focus on building user interfaces while React Query handles data management under the hood.</li><li>Automatic Caching: One of the standout features of React Query is its built-in caching mechanism. It caches query results by default, ensuring that subsequent requests for the same data are served from the cache rather than making redundant network calls. This improves the performance and responsiveness of applications, especially in scenarios where data doesn’t frequently change.</li><li>Automatic Background Data Refetching: React Query provides automatic background data refetching, ensuring that cached data remains fresh. We can configure data refetching intervals or trigger refetching based on specific conditions, guaranteeing that users always have access to the latest data without sacrificing performance.</li><li>Error Handling and Retry Strategies: React Query simplifies error handling by providing built-in mechanisms to handle errors gracefully. This allows us to define custom error handling logic and retry strategies which allow applications to recover from network failures or server errors seamlessly.</li></ol><h4>Key Components of React query</h4><p>QueryClientProvider — the top-level component wraps our React application, providing our application with a global context of the query client instance. It ensures that query-related functionality is available throughout the component tree.</p><pre>import { QueryClientProvider } from &#39;react-query&#39;;<br><br><br>function App() {<br>  return (<br>    &lt;QueryClientProvider&gt;<br>      {/* Your application components */}<br>    &lt;/QueryClientProvider&gt;<br>  );<br>}</pre><p>The QueryClientProvider receives a required client prop which is the QueryClient instance.</p><p>QueryClient — is the central hub for managing queries, caching data, and handling background data refetching. It serves as a global singleton instance that can be configured with various options to tailor its behavior according to your application’s needs.</p><pre>const queryClient = new QueryClient();</pre><p>The query client can be configured with certain options that help us specify how it should behave within our application.</p><pre>const queryClient = new QueryClient({<br>  defaultOptions: {<br>    queries: {<br>      retry: 1,<br>      staleTime: 30000, <br>      refetchOnWindowFocus: false,<br>    },<br>  },<br>});</pre><p>While react query offers a long list of options, in my experience the three in the snippet above are usually the most used.</p><p>retry — specifies the number of attempts we want react query to make before it gets a response from a query.</p><p>staleTime — time in milliseconds before considering data stale and attempting to get fresh data.</p><p>refetchOnWindowFocus — disables automatic refetching on window focus. By default this is true.</p><p>Putting these together, our root App component would look like this</p><pre>import { QueryClientProvider, QueryClient } from &#39;react-query&#39;;<br><br><br>const queryClient = new QueryClient({<br>  defaultOptions: {<br>    queries: {<br>      retry: 1,<br>      staleTime: 30000, <br>      refetchOnWindowFocus: false,<br>    },<br>  },<br>});<br><br>function App() {<br>  return (<br>    &lt;QueryClientProvider client={queryClient}&gt;<br>      {/* Your application components */}<br>    &lt;/QueryClientProvider&gt;<br>  );<br>}</pre><p>Let’s talk about the two core concepts of react-query.</p><p><strong>Mutations</strong> and <strong>Queries</strong>. These would be discussed in further detail in future parts of the series, but for now, an overview.</p><p><strong>Mutations</strong> are typically used to create/update/delete data or perform server side-effects. They are implemented via the useMutation hook and can only be in one of the following states at any given moment: isIdle isPending isError isSuccess . For clarity; isIdle is the state of a mutation when it is currently idle or in a fresh/reset state while isPending is the state of a currently running mutation. isError and isSuccess simply tell if the mutation failed of returned a success status.</p><p><strong>Queries</strong> are used with any Promise based method (including GET and POST methods) to fetch data from a server. Just like mutations, queries have states; isPending isError isSuccess there is also and isFetching state that is true anytime the query is fetching data — even in the background.</p><p>It is recommended to use mutations when we need to modify data on the server.</p><p>If you’re excited to get your hands dirty with react-query you go ahead to install and set it up in your react application.</p><pre>npm i @tanstack/react-query<br><br>pnpm add @tanstack/react-query<br><br>yarn add @tanstack/react-query<br><br>bun add @tanstack/react-query</pre><p>By understanding the key components and principles behind React Query, we can streamline data management in our applications and deliver better user experiences. Whether fetching data from APIs, handling real-time updates, or implementing complex data synchronization logic, React Query empowers developers to tackle data-related challenges with ease.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=181eb9c813de" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>