<?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 Rojan Maharjan on Medium]]></title>
        <description><![CDATA[Stories by Rojan Maharjan on Medium]]></description>
        <link>https://medium.com/@roseonmhr?source=rss-bb3cca594692------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*VpMSLFWgweBZzrqhO3GOkw.jpeg</url>
            <title>Stories by Rojan Maharjan on Medium</title>
            <link>https://medium.com/@roseonmhr?source=rss-bb3cca594692------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 24 Nov 2026 17:18:49 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@roseonmhr/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[Why useEffect is a bad place to make API calls]]></title>
            <link>https://articles.wesionary.team/why-useeffect-is-a-bad-place-to-make-api-calls-98a606735c1c?source=rss-bb3cca594692------2</link>
            <guid isPermaLink="false">https://medium.com/p/98a606735c1c</guid>
            <category><![CDATA[useeffect]]></category>
            <category><![CDATA[react]]></category>
            <dc:creator><![CDATA[Rojan Maharjan]]></dc:creator>
            <pubDate>Tue, 27 Sep 2022 12:23:15 GMT</pubDate>
            <atom:updated>2022-09-27T12:23:15.538Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aE0jkOOH0nCYjwT88tdw1Q.png" /></figure><p>The design choices react team have made in useEffect hook are still a heated debate. Some people like it and some don’t.</p><p>If you don&#39;t come from the React world it’ll definitely sound strange because its default behaviour is the dreaded “Infinite Render Loop” which is pretty easy to run into. For example</p><pre>useEffect(()=&gt;{console.log(&quot;Hello World&quot;)})</pre><p>Looks fine right?<br>Nope, this will print “Hello World” in every render and the React dev OCD in me can&#39;t wait to put a second dependency array like this</p><pre>useEffect(()=&gt;{console.log(&quot;Hello World&quot;)},[])</pre><p>So we have to always make sure it doesn&#39;t run into an infinite loop manually every time we use it.</p><p>And that&#39;s it, we fixed the problem and the code above should only run once right?<br>Technically but not always…</p><h3>The strict mode problem</h3><p>In development mode, if you want the benefits of the <a href="https://reactjs.org/docs/strict-mode.html">react strict mode</a> this will actually be called twice.</p><p>You can already see why this is a problem. Take this code for example</p><pre>useEffect(()=&gt;{<br>  api.post(&quot;/view&quot;,{})<br>},[])</pre><p>Let&#39;s say we have a code that sends an event that says, the user viewed the page like in the above useEffect. React on strict mode will run this effect twice and send a double event.</p><p>You can make hacky work around with refs like below</p><pre>export default function useEffectOnce(fn: () =&gt; void) {<br>  const ref = useRef(false);<br>  useEffect(() =&gt; {<br>    if (ref.current) {<br>      fn();<br>    }<br>    return () =&gt; {<br>      ref.current = true;<br>    };<br>  }, [fn]);<br>}</pre><p>But inherently this is an issue and is not an elegant fix, to say the least.</p><h3>The performance problem</h3><p>According to the <a href="https://reactjs.org/docs/hooks-effect.html">official docs</a> the useEffect hook runs after the rendering of the entire UI or component completes. So when we put an API call in it, the API call will start after the complete rendering of UI completes as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QJeFp2zDfLbnNdU-MObUzQ.png" /></figure><p>This is not optimal as although react is fast rendering UI will always consume some time and it will delay our API call which could just as well run on the start of the render.</p><p>So the better approach would be fetching data and rendering it parallelly.</p><p>How do we do that?</p><h3>React Query to the rescue</h3><p>React query does exactly what we discussed, the hooks like <a href="https://tanstack.com/query/v4/docs/reference/useQuery?from=reactQueryV3">useQuery</a> fetch data as soon as rendering starts so you don’t have to wait until react loads the entire component as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5lR34PwkqAvrZcA5p4YbPw.png" /></figure><p>Here is an example</p><pre>// with react query<br>const { status, data, error, isFetching } = useQuery(<br>  [&#39;data&#39;],<br>  async () =&gt; {<br>    const data = await (<br>      await fetch(`${API_BASE_URL}/data`)<br>    ).json()<br>    return data<br>  }<br>)</pre><pre>// without react query<br>useEffect(() =&gt; {<br>  try {<br>    setLoading(true)(async () =&gt; {<br>      const data = await (await fetch(`${API_BASE_URL}/data`)).json();<br>      setData(data);<br>    })();<br>  } catch (error) {<br>    setError(error);<br>  } finally {<br>    setLoading(false);<br>  }<br>}, []);</pre><p>Looking at the syntax we can see that react query use query not only executes instantly as the page loads but also handles a lot of things like loading states, error states and actual data in a single object returned by react query.<br> Furthermore, rerunning/invalidating the query is as simple as.</p><pre>queryClient.invalidateQueries([&#39;data&#39;])</pre><p>Some other notable libraries that also solve the problems are <a href="https://swr.vercel.app/">SWR</a>, <a href="https://swr.vercel.app/">URQL</a> and <a href="https://www.apollographql.com/docs/react">Apollo Client</a>.</p><p>Another way of solving the issue is by doing SSR so data already renders on the backend or even using features like <a href="https://reactrouter.com/en/dev/route/loader">react-router loaders</a>.</p><h3>Conclusion</h3><p>Making API calls on useEffects can be error-prone or downright slow. So it&#39;s best to avoid it unless you certainly have to. You really want some library to handle the data fetching for you.</p><h3>References:</h3><ul><li><a href="https://www.youtube.com/watch?v=95B8mnhzoCM">When To Fetch: Remixing React Router — Ryan Florence</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=98a606735c1c" width="1" height="1" alt=""><hr><p><a href="https://articles.wesionary.team/why-useeffect-is-a-bad-place-to-make-api-calls-98a606735c1c">Why useEffect is a bad place to make API calls</a> was originally published in <a href="https://articles.wesionary.team/">wesionaryTEAM</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building smart 404 pages in NextJS]]></title>
            <link>https://articles.wesionary.team/building-smart-404-pages-in-nextjs-63fc5f10912b?source=rss-bb3cca594692------2</link>
            <guid isPermaLink="false">https://medium.com/p/63fc5f10912b</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[fuzzy-matching]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[nextjs]]></category>
            <category><![CDATA[404-page]]></category>
            <dc:creator><![CDATA[Rojan Maharjan]]></dc:creator>
            <pubDate>Thu, 22 Sep 2022 10:47:26 GMT</pubDate>
            <atom:updated>2022-09-23T02:29:41.940Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HkdCxAEmX6PgXGScSILCHA.png" /></figure><p>404 pages, everyone has seen them to the point they are a meme. Every site needs them but not a lot of thought goes into making them (except for one below of-course).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*XzxaXgx-mJSU0Lma.png" /><figcaption>credit <a href="https://dribbble.com/gonzamoreira">Gonza Moreira</a></figcaption></figure><h4>Essence of the 404 page</h4><p>When a user sees a 404 page it means a user is expecting a content that should exist on your site but it doesn’t. This could happen because multiple reasons including typos, broken URLs, deleted content and so on.</p><p>Inherently a 404 page means the user is lost. The user can no longer proceed with your intended flow of the site and is stuck.</p><h3>How can we help the user ?</h3><blockquote>URLs are ugly to look at, hard to remember, and a nightmare for security. Still, they are the entire point of the web -Allen Pike</blockquote><p>Most common way to face a 404 page is to mess up a URL. So, what if a 404 page solved this issue.</p><h4>URL aware 404 pages</h4><p>In an ideal world you’d never want to see a 404 page. But that is not the case. Next best thing is a 404 page that leads you to the right one.</p><h3>Lets Build</h3><p>We will be using <a href="https://nextjs.org/">NextJs</a> with js for simplicity. But the base principles can be applied to any platform.</p><p>Create your next app with following:</p><pre>yarn create next-app</pre><p>Now lets install fuse.js and glob</p><pre>yarn add fuse.js glob</pre><p>Create a 404.jsx file in pages folder:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/390/1*NUpcga7Ak-imzSgtcUUClQ.png" /></figure><p>Write down your boilerplate jsx</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5ba1c4b7640a658bf609b3863b74dc7b/href">https://medium.com/media/5ba1c4b7640a658bf609b3863b74dc7b/href</a></iframe><p>Let’s start the fun part.</p><p>A next.js app uses path based routing meaning all the files in /pages directory are actually routes. So if we get just get the file paths they are all the routes that exists. So we do exactly that here.</p><p>Lets add the following <a href="https://nextjs.org/docs/basic-features/data-fetching/get-static-props">getStaticProps</a> method:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d5fe99976d0dc15f9ec68a3584c9906d/href">https://medium.com/media/d5fe99976d0dc15f9ec68a3584c9906d/href</a></iframe><p>Here we are using <a href="https://www.npmjs.com/package/glob">glob</a> to scan for files with .js extension in the pages directory. Then we’re stripping extensions and ignoring next js specific files and api routes. The pages we get now the are sent as props.</p><p>Now we add a use effect as follows:</p><pre>const NotFoundPage = ({ pages }) =&gt; {<br>  const [results, setResults] = useState([]);<br>  const router = useRouter();</pre><pre>  useEffect(() =&gt; {<br>    const fuse = new Fuse(pages);<br>    const searchResults = fuse.search(router.asPath);<br>    setResults(searchResults.map((result) =&gt; result.item));<br>  }, [pages, router.asPath]);</pre><pre>....</pre><p>Here we are initializing Fuse.js which is a fuzzy searching library with all our pages prop and searching the current route path on it. Then we add all the results to our results state.</p><p>Now to test it. Create a few test pages/routes</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/352/1*FWyIDa6794EqDbB2v0LkUQ.png" /></figure><p>Now open a URL that results in 404 (I open <a href="http://localhost:3000/es">http://localhost:3000/es</a>) and here it is :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EjDBBqc4PydsvWA8n2CWKQ.png" /></figure><p>It suggested the pages similar our route url i.e. test and register.</p><p>Note: If your URL doesn’t show its because because NextJS doesn’t generate .js file on development mode until you open them. This is a non issue after build so it works if you just do:</p><pre>next build &amp;&amp; next start</pre><p>Finally since we use getStaticProps to get the pages this works even if you have a static hosting.</p><p>Entire project is in git hub if you need to look into the code:<br><a href="https://github.com/symetryn/Smart-404-page">https://github.com/symetryn/Smart-404-page</a></p><p>Happy Coding!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=63fc5f10912b" width="1" height="1" alt=""><hr><p><a href="https://articles.wesionary.team/building-smart-404-pages-in-nextjs-63fc5f10912b">Building smart 404 pages in NextJS</a> was originally published in <a href="https://articles.wesionary.team/">wesionaryTEAM</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>