<?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 Onur Önder on Medium]]></title>
        <description><![CDATA[Stories by Onur Önder on Medium]]></description>
        <link>https://medium.com/@onderonur?source=rss-c091e96bb961------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*JCL_rRheFPxAlvfV.jpg</url>
            <title>Stories by Onur Önder on Medium</title>
            <link>https://medium.com/@onderonur?source=rss-c091e96bb961------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 21 Nov 2026 20:55:15 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@onderonur/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[Creating a TypeScript Package with Vite]]></title>
            <link>https://onderonur.medium.com/creating-a-typescript-package-with-vite-86a798ff3066?source=rss-c091e96bb961------2</link>
            <guid isPermaLink="false">https://medium.com/p/86a798ff3066</guid>
            <category><![CDATA[npm]]></category>
            <category><![CDATA[vitejs]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[npm-package]]></category>
            <dc:creator><![CDATA[Onur Önder]]></dc:creator>
            <pubDate>Mon, 24 Oct 2022 21:23:13 GMT</pubDate>
            <atom:updated>2023-02-23T19:03:09.555Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/680/0*Aq_2oLwjMznHKtpn.jpg" /></figure><p>Sometimes, we have some utility functions or some complex stuff that we need to use in multiple projects and we don’t want to copy it to each and every project. Or sometimes we just want to contribute to open-source community to both improve ourselves and help others.</p><p>There are a lot of different ways of creating a TypeScript package. And here is a simple tutorial to make it happen by using <a href="https://vitejs.dev/">Vite</a>.</p><p>We are gonna create a simple utility package with a couple of functions. And it can be used both for frontend and backend.</p><p><strong>Note:</strong> Here are the package versions used in this tutorial. When a new version is published, some of these may have breaking changes, change of best practices, have new options/usages etc. It is <strong>always</strong> nice to check the original documentation of the tools we are using every now and then.</p><pre>&quot;@types/node&quot;: &quot;^18.14.0&quot;,<br>&quot;typescript&quot;: &quot;^4.9.3&quot;,<br>&quot;vite&quot;: &quot;^4.1.0&quot;,<br>&quot;vite-plugin-dts&quot;: &quot;^1.7.3&quot;</pre><p>For testing with Jest:</p><pre>&quot;@types/jest&quot;: &quot;^29.4.0&quot;,<br>&quot;jest&quot;: &quot;^29.4.3&quot;,<br>&quot;ts-jest&quot;: &quot;^29.0.5&quot;,</pre><h3>Scaffolding the Project</h3><p>First of all, we need to <a href="https://vitejs.dev/guide/#scaffolding-your-first-vite-project">create a new Vite project</a>. To accomplish this, we can run the following command:</p><pre>npm create vite@latest</pre><p>It will ask us some questions to create our project. We can set them like below:</p><pre>Project name: my-ts-lib<br>Select a framework: Vanilla<br>Select a variant: TypeScript</pre><p>It will have a folder structure like this:</p><pre>📦my-ts-lib<br> ┣ 📂public<br> ┃ ┗ 📜vite.svg<br> ┣ 📂src<br> ┃ ┣ 📜counter.ts<br> ┃ ┣ 📜main.ts<br> ┃ ┣ 📜style.css<br> ┃ ┣ 📜typescript.svg<br> ┃ ┗ 📜vite-env.d.ts<br> ┣ 📜.gitignore<br> ┣ 📜index.html<br> ┣ 📜package.json<br> ┗ 📜tsconfig.json</pre><p>We can delete index.html, public folder and all the files in src. In the end, it will look this this:</p><pre>📦my-ts-lib<br> ┣ 📂src<br> ┣ 📜.gitignore<br> ┣ 📜package.json<br> ┗ 📜tsconfig.json</pre><p>Now, install the dependencies by using:</p><pre>npm install</pre><h3>Implementing the Features</h3><p>Now, we can implement our utility functions and create a simple folder structure.</p><pre>// src/sum.ts<br>function sum(a: number, b: number) {<br>  return a + b;<br>}<br><br>export default sum;</pre><pre>// src/subtract.ts<br>function subtract(a: number, b: number) {<br>  return a - b;<br>}<br>export default subtract;</pre><pre>// src/index.ts<br>export { default as sum } from &#39;./sum&#39;;<br>export { default as subtract } from &#39;./subtract&#39;;</pre><p>The key point here is, exporting all the functions, constants, enums, types etc. by using index.ts file. We are gonna point to it (actually, the output based on it) in our package.json in the following steps. So, we can say that, this is the place where we describe all the things we expose to the outside world and let other developers to be able to use this package.</p><p>There can be multiple entry points for a package, but this is not a topic of this tutorial. For this, we can check <a href="https://vitejs.dev/guide/build.html#library-mode">Vite Library Mode documentation</a>.</p><p><strong>Note:</strong> We could create a single index.ts file and put all our code in it. But we just created multiple files to see how it affects the structure. The topics like the folder structure and how we export our functions (named or default export etc.) are completely up to us. We can sort out how to structure the project as it grows. There are also some recommended approaches which are worth for checking.</p><h3>Bundling the Package</h3><p>To create the distributable package to publish on <a href="https://www.npmjs.com/">npm</a>, we need to create a vite.config.ts at the root of the project first. But before that, we need to install a couple more dependencies to get ready.</p><p>Since we are gonna use some Node.js modules like path, we need no install @types/node. And to be able to include our type definitions as .d.ts files to our bundle, we need vite-plugin-dts.</p><p>We need these packages only for local development or testing our package. So we put them in our devDependencies by --save-dev or -D flag. For more information about dependencies, devDependencies and peerDependencies, we can check <a href="https://docs.npmjs.com/specifying-dependencies-and-devdependencies-in-a-package-json-file">npm Docs</a>.</p><pre>npm install -D @types/node vite-plugin-dts</pre><pre>// vite.config.ts<br>import { resolve } from &#39;path&#39;;<br>import { defineConfig } from &#39;vite&#39;;<br>import dts from &#39;vite-plugin-dts&#39;;<br><br>// https://vitejs.dev/guide/build.html#library-mode<br>export default defineConfig({<br>  build: {<br>    lib: {<br>      entry: resolve(__dirname, &#39;src/index.ts&#39;),<br>      name: &#39;my-lib&#39;,<br>      fileName: &#39;my-lib&#39;,<br>    },<br>  },<br>  plugins: [dts()],<br>});</pre><p>And we need to add the entry points of our package to package.json. We also need to remove private field from it, if there is one.</p><pre>// package.json<br>{<br>  &quot;name&quot;: &quot;my-ts-lib&quot;,<br>  &quot;version&quot;: &quot;0.0.0&quot;,<br>  &quot;type&quot;: &quot;module&quot;,<br>  &quot;main&quot;: &quot;./dist/my-lib.umd.cjs&quot;,<br>  &quot;module&quot;: &quot;./dist/my-lib.js&quot;,<br>  &quot;types&quot;: &quot;./dist/index.d.ts&quot;,<br>  &quot;exports&quot;: {<br>    &quot;.&quot;: {<br>      &quot;import&quot;: &quot;./dist/my-lib.js&quot;,<br>      &quot;require&quot;: &quot;./dist/my-lib.umd.cjs&quot;<br>    }<br>  },<br>  // ...<br>}</pre><p>Basically, we are pointing out the root of our package and where the types are (by type field). Even if it&#39;s not the full explanation, we can basically think that when someone uses our package by using import ... from &#39;my-ts-lib&#39; and if it runs in an environment which supports ECMAScript modules (ESM), more modern ESM version of our code will be used. Otherwise, if someone uses our package by using require(&#39;my-ts-lib&#39;), it will use the CommonJS (CJS) version.</p><p>Now, we are ready to build our package and see the first result. Let’s run the build command:</p><pre>npm run build</pre><p>It will create a dist folder at the root of our project and it will look like this:</p><pre>📦dist<br> ┣ 📜index.d.ts<br> ┣ 📜my-lib.js<br> ┣ 📜my-lib.umd.cjs<br> ┣ 📜subtract.d.ts<br> ┗ 📜sum.d.ts</pre><p>It looks fine for now. But we need to add a couple of more stuff before publishing it to npm.</p><p>First of all, we need a README.md file to inform other developers about how to use this package, showing examples etc. It will be shown on the page of our package on npm.</p><p>We will create the README.md file at the root of the project. It can have any type of information we want.</p><pre># my-ts-lib<br><br>This is a package created to practice building a TypeScript package with Vite.</pre><p>We also need to create a LICENSE file too. We can check <a href="https://docs.github.com/en/repositories/managing-your-repositorys-settings-and-features/customizing-your-repository/licensing-a-repository">licensing a repository</a> docs of GitHub to have a little knowledge about it.</p><p>And lastly, we need to add a files field to package.json to indicate npm what we want to be in the final package. We just need to point dist folder here. README.md, LICENSE and package.json will be automatically included. If we come across any problem, we can put them in this array too.</p><pre>  // package.json<br>  // ...<br>  &quot;main&quot;: &quot;./dist/my-lib.umd.cjs&quot;,<br>  &quot;module&quot;: &quot;./dist/my-lib.js&quot;,<br>  &quot;types&quot;: &quot;./dist/index.d.ts&quot;,<br>  &quot;exports&quot;: {<br>    &quot;.&quot;: {<br>      &quot;import&quot;: &quot;./dist/my-lib.js&quot;,<br>      &quot;require&quot;: &quot;./dist/my-lib.umd.cjs&quot;<br>    }<br>  },<br>  &quot;files&quot;: [<br>    &quot;dist&quot;<br>  ],<br>  // ...</pre><p>And now, we can run the following command to preview what our package will look like without publishing it:</p><pre>npm pack --dry-run</pre><p><a href="https://docs.npmjs.com/cli/v7/commands/npm-pack">npm pack</a> command helps us to preview what our package will include and its size when we publish it. --dry-run is optional here. If we don&#39;t use it and just run npm pack, it will also create a .tgz file which is what would be deployed on npm. We are just previewing our package without publishing it, yet. We can use this command at anytime to preview our package.</p><pre>npm notice 📦  my-ts-lib@0.0.0<br>npm notice === Tarball Contents ===<br>npm notice 1.1kB LICENSE<br>npm notice 95B   README.md<br>npm notice 90B   dist/index.d.ts<br>npm notice 114B  dist/my-lib.js<br>npm notice 392B  dist/my-lib.umd.cjs<br>npm notice 82B   dist/subtract.d.ts<br>npm notice 72B   dist/sum.d.ts<br>npm notice 554B  package.json<br>npm notice === Tarball Details ===<br>npm notice name:          my-ts-lib<br>npm notice version:       0.0.0<br>npm notice filename:      my-ts-lib-0.0.0.tgz<br>npm notice package size:  1.6 kB<br>npm notice unpacked size: 2.5 kB<br>npm notice total files:   8</pre><p>We have dist folder, README.md, LICENSE and package.json in our package. Just like we want.</p><h3>Versioning</h3><p>As we can see, our package version is 0.0.0 now. We might want to update our package version, especially as we add new features, make fixes or refactors. <a href="https://semver.org/">Semantic Versioning</a> is a nice way to follow for this. We can use following commands to bump our package version:</p><pre>npm version patch<br># Bumps the patch number like 0.0.0 -&gt; 0.0.1<br><br>npm version minor<br># Bumps the patch number like 0.0.x -&gt; 0.1.0<br><br>npm version major<br># Bumps the patch number like 0.x.y -&gt; 1.0.0</pre><p>We can also use alpha or beta versions. <a href="https://docs.npmjs.com/cli/v8/commands/npm-version">npm version Docs</a> is a nice place to check out for it.</p><h3>Setting Up Tests</h3><p>We may want to test our package to be sure if it’s reliable and we’re not breaking anything in time. To do that, we need to install some packages to be used for testing.</p><p>We can use the good old <a href="https://jestjs.io/">Jest</a> or <a href="https://vitest.dev/">Vitest</a> for testing. It’s up to you to choose the one you like.</p><h3>Testing with Jest</h3><p>First, we need to install the packages required for testing.</p><pre>npm install -D jest @types/jest ts-jest</pre><p>And we need to create a jest.config.js file to configure Jest to test our ts files.</p><pre>npx ts-jest config:init</pre><p>Lastly, we need to add a test script to our package.json.</p><pre>// package.json<br>{<br>  // ...<br>  &quot;scripts&quot;: {<br>    &quot;dev&quot;: &quot;vite&quot;,<br>    &quot;build&quot;: &quot;tsc &amp;&amp; vite build&quot;,<br>    &quot;preview&quot;: &quot;vite preview&quot;,<br>    &quot;test&quot;: &quot;jest&quot;<br>  },<br>  // ...<br>}</pre><p>Now, we can create our test files and see if our package works properly.</p><pre>// src/sum.test.ts<br>import sum from &#39;./sum&#39;;<br><br>test(&#39;sums two numbers&#39;, () =&gt; {<br>  expect(sum(4, 7)).toBe(11);<br>});</pre><pre>// src/subtract.test.ts<br>import subtract from &#39;./subtract&#39;;<br><br>test(&#39;subtracts two numbers&#39;, () =&gt; {<br>  expect(subtract(10, 7)).toBe(3);<br>});</pre><p>Let’s run our test and see if we’re all good:</p><pre>npm test</pre><p>🎉🎉🎉</p><pre>Test Suites: 2 passed, 2 total<br>Tests:       2 passed, 2 total</pre><h3>Testing with Vitest</h3><p>As the first step, we will install Vitest.</p><pre>npm install -D vitest</pre><p>Also, even if it’s not required for this example, we can configure it in our vite.config.ts.</p><pre>// vite.config.ts<br><br>/// &lt;reference types=&quot;vitest&quot; /&gt;<br>// Configure Vitest (https://vitest.dev/config/)<br><br>import { resolve } from &quot;path&quot;;<br>import { defineConfig } from &quot;vite&quot;;<br>import dts from &quot;vite-plugin-dts&quot;;<br><br>// https://vitejs.dev/guide/build.html#library-mode<br>export default defineConfig({<br>  build: {<br>    lib: {<br>      entry: resolve(__dirname, &quot;src/index.ts&quot;),<br>      name: &quot;my-lib&quot;,<br>      fileName: &quot;my-lib&quot;,<br>    },<br>  },<br>  plugins: [dts()],<br>  test: {<br>    // ...<br>  },<br>});</pre><p>We will add test script to package.json:</p><pre><br>// package.json<br>{<br>  // ...<br>  &quot;scripts&quot;: {<br>    &quot;dev&quot;: &quot;vite&quot;,<br>    &quot;build&quot;: &quot;tsc &amp;&amp; vite build&quot;,<br>    &quot;preview&quot;: &quot;vite preview&quot;,<br>    &quot;test&quot;: &quot;vitest&quot;<br>  },<br>  // ...<br>}</pre><p>Create our test files to be sure our package works properly:</p><pre>// src/sum.test.ts<br>import { test, expect } from &#39;vitest&#39;;<br>import sum from &#39;./sum&#39;;<br><br>test(&#39;sums two numbers&#39;, () =&gt; {<br>  expect(sum(4, 7)).toBe(11);<br>});</pre><pre>// src/subtract.test.ts<br>import { test, expect } from &#39;vitest&#39;;<br>import subtract from &#39;./subtract&#39;;<br><br>test(&#39;subtracts two numbers&#39;, () =&gt; {<br>  expect(subtract(10, 7)).toBe(3);<br>});</pre><p>And we can run the tests to see if everything is fine.</p><pre>npm test</pre><p>🎉🎉🎉</p><pre>Test Files  2 passed (2)<br>     Tests  2 passed (2)</pre><h3>Linting &amp; Formatting</h3><p>We may want to lint our code for finding problems and format it to have a well structured project.</p><p>To do this, a good way is using <a href="https://eslint.org/">ESLint</a> and <a href="https://prettier.io/">Prettier</a>.</p><p>This tutorial will not be deep dive about how to set these up. Rules, plugins and configs may differ based on the project and team preferences. Like mentioned at the beginning, official docs of these kind of tools are the best places to check out.</p><p>But as a couple of advices, a fast way of setting ESLint up is using the following command:</p><pre>npx eslint --init</pre><p>And if we want to use Prettier with it, <a href="https://github.com/prettier/eslint-plugin-prettier">eslint-plugin-prettier</a> and <a href="https://github.com/prettier/eslint-config-prettier">eslint-config-prettier</a> are worth checking.</p><p>Also, <a href="https://typicode.github.io/husky/#/">Husky</a> and <a href="https://github.com/okonet/lint-staged">lint-staged</a> are nice tools to have a more more strict and automated flow for linting and formatting.</p><h3>Publishing the Package</h3><p>We are nearly there. We just need to add a couple of more fields to inform npm about our package.</p><pre>// package.json<br>{<br>  // ...<br>  &quot;description&quot;: &quot;This is a simple utility package&quot;,<br>  &quot;author&quot;: &quot;&lt;YOUR_NAME&gt;&quot;,<br>  &quot;license&quot;: &quot;MIT&quot;,<br>  &quot;homepage&quot;: &quot;&lt;YOUR_SITE_URL&gt;&quot;,<br>  &quot;repository&quot;: {<br>    &quot;type&quot;: &quot;git&quot;,<br>    &quot;url&quot;: &quot;https://github.com/&lt;YOUR_USER_NAME&gt;/my-ts-lib.git&quot;<br>  },<br>  &quot;bugs&quot;: {<br>    &quot;url&quot;: &quot;https://github.com/&lt;YOUR_USER_NAME&gt;/my-ts-lib/issues&quot;<br>  },<br>  &quot;keywords&quot;: [&quot;some&quot;, &quot;keywords&quot;, &quot;to&quot;, &quot;describe&quot;, &quot;the&quot;, &quot;package&quot;],<br>  // ...<br>}</pre><p>And finally, we use <a href="https://docs.npmjs.com/cli/v8/commands/npm-publish">npm publish</a> command and publish our package to npm:</p><pre>npm publish</pre><p>Thanks for reading!</p><p><em>Originally published at </em><a href="https://onderonur.netlify.app/blog/creating-a-typescript-library-with-vite/"><em>https://onderonur.netlify.app</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=86a798ff3066" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Calculate Values Based on Props or State in React]]></title>
            <link>https://onderonur.medium.com/how-to-calculate-values-based-on-props-or-state-in-react-df27d642bbd3?source=rss-c091e96bb961------2</link>
            <guid isPermaLink="false">https://medium.com/p/df27d642bbd3</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[props-and-state]]></category>
            <category><![CDATA[state-management]]></category>
            <category><![CDATA[front-end-development]]></category>
            <dc:creator><![CDATA[Onur Önder]]></dc:creator>
            <pubDate>Sun, 01 May 2022 15:52:06 GMT</pubDate>
            <atom:updated>2022-05-07T11:27:25.987Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/680/0*CMeyfu2O4ftg9KL0.jpg" /></figure><p>When we think about React and what it does, it all comes to creating a UI in a declarative way if we simplify it. When it comes to calculating dynamic values based on props or some state, there are some common mistakes done by both beginners and experienced developers. We are gonna talk about one of these.</p><p>Let’s think we have a component which renders a list of posts like:</p><pre>function PostList({ posts }) {<br>  return (<br>    &lt;div&gt;<br>      &lt;Title&gt;Posts&lt;/Title&gt;<br>      &lt;List&gt;<br>        {posts.map((post) =&gt; {<br>          return (<br>            &lt;ListItem key={post.id}&gt;<br>              &lt;PostAuthor author={post.author} /&gt;<br>              &lt;PostDate&gt;{post.createdAt}&lt;/PostDate&gt;<br>              &lt;PostBody&gt;{post.body}&lt;/PostBody&gt;<br>              &lt;Actions&gt;<br>                &lt;LikeButton postId={post.id} likeCount={post.likeCount} /&gt;<br>              &lt;/Actions&gt;<br>            &lt;/ListItem&gt;<br>          );<br>        })}<br>      &lt;/List&gt;<br>    &lt;/div&gt;<br>  );<br>}</pre><p>Nothing fancy here. Just a simple component which composes different sub-components to render a post list.</p><p>Now let’s think that, we need to show the total like count of all of the posts right under the title. We have the posts array and each post has a likeCount. Obviously, we need the summary of these fields and change that total value as posts array is changed. We can use any method (e.g., Array.forEach, Array.reduce, plain for loop etc.) to iterate posts array to get the total like count. Let&#39;s keep it simple and clear. So we can do something like this:</p><pre>// We can put this function in `PostList` component to make it directly access `posts` prop and use `useCallback`.<br>// But this is not the case here, and let&#39;s just keep things simple.<br>// We just have a function to calculate total like count.function getTotalLikeCount(posts) {<br>  let totalLikeCount = 0;<br>  posts.forEach((post) =&gt; {<br>    totalLikeCount = totalLikeCount + post.likeCount;<br>  });<br>  return totalLikeCount;<br>}</pre><pre>function PostList({ posts }) {<br>  const [totalLikeCount, setTotalLikeCount] = useState(<br>    getTotalLikeCount(posts),<br>  );</pre><pre>  useEffect(() =&gt; {<br>    const newTotalLikeCount = getTotalLikeCount(posts);<br>    setTotalLikeCount(newTotalLikeCount);<br>  }, [posts]);</pre><pre>  return (<br>    &lt;div&gt;<br>      &lt;Title&gt;Posts&lt;/Title&gt;<br>      &lt;Subtitle&gt;Total Likes: {totalLikeCount}&lt;/Subtitle&gt;<br>      &lt;List&gt;<br>        {posts.map((post) =&gt; {<br>          return (<br>            &lt;ListItem key={post.id}&gt;<br>              &lt;PostAuthor author={post.author} /&gt;<br>              &lt;PostDate&gt;{post.createdAt}&lt;/PostDate&gt;<br>              &lt;PostBody&gt;{post.body}&lt;/PostBody&gt;<br>              &lt;Actions&gt;<br>                &lt;LikeButton postId={post.id} likeCount={post.likeCount} /&gt;<br>              &lt;/Actions&gt;<br>            &lt;/ListItem&gt;<br>          );<br>        })}<br>      &lt;/List&gt;<br>    &lt;/div&gt;<br>  );<br>}</pre><p>This will work as expected. We are updating totalLikeCount state as posts array is changed and it also looks very simple. So, everything should be OK, right? But actually, we did something &quot;wrong&quot; here. As you can see, we created a new state called totalLikeCount to update the UI as posts array is changed to show the current total like count.</p><p>totalLikeCount is directly calculated based on a prop, which is posts. We can calculate it dynamically without creating a new state. We don&#39;t need to update totalLikeCount to re-render the UI. It will already re-render when posts is changed. We don&#39;t need to do anything imperative like this to make React to re-render this component.</p><p>This kind of useState + useEffect usage is a very common mistake. I guess, we just forget that React is based on declarative approaches and think we need to make some sort of a state update to make it re-render the components. Using useState + useEffect will end up creating a flow like:</p><ul><li>posts prop is changed.</li><li>PostList component gets re-rendered.</li><li>useEffect gets triggered and calls setTotalLikeCount.</li><li>Since a state is changed (assuming newTotalLikeCount is different than the current totalLikeCount), component gets re-rendered again.</li></ul><p>So, it ended up creating an unnecessary re-render and we got an unnecessary flow. You may even see some sort of a flickering for the Subtitle component content and try to use useLayoutEffect, but it&#39;s not the right solution here.</p><p>We can apply different solutions based on our requirements.</p><h3>Improvement 1 — Updating State During Render</h3><p>As we mentioned, when posts prop is changed PostList components gets re-rendered and after the rendering process is finished, useEffect gets triggered. Because we called setTotalLikeCount in that useEffect, if we set a value different than the current totalLikeCount, PostList will be re-rendered again.</p><p>So, instead of waiting for the first render to be done and updating totalLikeCount after that, we can update it during the first rendering process.</p><p>Updating a state during render seems a little bad at first. But it’s basically what getDerivedStateFromProps was doing in class components. You can check <a href="https://reactjs.org/docs/hooks-faq.html#how-do-i-implement-getderivedstatefromprops">the official React docs</a> to understand it better.</p><p>We can simply do:</p><pre>function getTotalLikeCount(posts) {<br>  let totalLikeCount = 0;<br>  posts.forEach((post) =&gt; {<br>    totalLikeCount = totalLikeCount + post.likeCount;<br>  });<br>  return totalLikeCount;<br>}</pre><pre>function PostList({ posts }) {<br>  const [totalLikeCount, setTotalLikeCount] = useState(<br>    getTotalLikeCount(posts),<br>  );<br>  const [prevPosts, setPrevPosts] = useState(posts);</pre><pre>  if (posts !== prevPosts) {<br>    setPrevPosts(posts);<br>    setTotalLikeCount(getTotalLikeCount(posts));<br>  }</pre><pre>  return (<br>    &lt;div&gt;<br>      &lt;Title&gt;Posts&lt;/Title&gt;<br>      &lt;Subtitle&gt;Total Likes: {totalLikeCount}&lt;/Subtitle&gt;<br>      &lt;List&gt;<br>        {posts.map((post) =&gt; {<br>          return (<br>            &lt;ListItem key={post.id}&gt;<br>              &lt;PostAuthor author={post.author} /&gt;<br>              &lt;PostDate&gt;{post.createdAt}&lt;/PostDate&gt;<br>              &lt;PostBody&gt;{post.body}&lt;/PostBody&gt;<br>              &lt;Actions&gt;<br>                &lt;LikeButton postId={post.id} likeCount={post.likeCount} /&gt;<br>              &lt;/Actions&gt;<br>            &lt;/ListItem&gt;<br>          );<br>        })}<br>      &lt;/List&gt;<br>    &lt;/div&gt;<br>  );<br>}</pre><p>By using this technique, we simply made a little performance optimization and told React to exit the current rendering process if posts is changed during that render and start a new render with updated totalLikeCount. We can even create a useDerivedState hook if we need to use this approach in multiple places. But should we use this approach all the time?</p><p>We still have an unnecessary flow here. Even if we exit the first render, we still set totalLikeCount as a state of PostList component. This kind of an approach may be valuable for cases like creating a form component. If we want to derive some default/initial values based on props (or other state) and be able to update those values with some user interaction etc. (a common case for form components), this could be what we use. But even in that case, there are better alternatives like using a key on the form component. We will not deep-dive into it in this article but using a simple key and telling React to throw the current component into thrash as that key changes and create a new one is a very simple, maintainable and performant way instead of manually resetting states of that component in many cases. You can read about this in <a href="https://reactjs.org/blog/2018/06/07/you-probably-dont-need-derived-state.html">here</a> and see if you really need to use derived state.</p><h3>Improvement 2 — Not Using State at All</h3><p>In our case totalLikeCount is a read-only value. We don&#39;t have a case to update it manually. Even if we would want to use techniques like optimistic UI, we would do it directly on posts array based on the approach we use to get it (Context API, Redux, React Query, SWR, Apollo etc.). totalLikeCount is a value, which should be derived from posts. Just because it should be derived from some prop (or state), we should not make it a state if we don&#39;t need it really.</p><p>So we can simply calculate it in the render scope like:</p><pre>function getTotalLikeCount(posts) {<br>  let totalLikeCount = 0;<br>  posts.forEach((post) =&gt; {<br>    totalLikeCount = totalLikeCount + post.likeCount;<br>  });<br>  return totalLikeCount;<br>}</pre><pre>function PostList({ posts }) {<br>  // No useState, no useEffect, just a dynamically calculated value.<br>  const totalLikeCount = getTotalLikeCount(posts);</pre><pre>return (<br>    &lt;div&gt;<br>      &lt;Title&gt;Posts&lt;/Title&gt;<br>      &lt;Subtitle&gt;Total Likes: {totalLikeCount}&lt;/Subtitle&gt;<br>      &lt;List&gt;<br>        {posts.map((post) =&gt; {<br>          return (<br>            &lt;ListItem key={post.id}&gt;<br>              &lt;PostAuthor author={post.author} /&gt;<br>              &lt;PostDate&gt;{post.createdAt}&lt;/PostDate&gt;<br>              &lt;PostBody&gt;{post.body}&lt;/PostBody&gt;<br>              &lt;Actions&gt;<br>                &lt;LikeButton postId={post.id} likeCount={post.likeCount} /&gt;<br>              &lt;/Actions&gt;<br>            &lt;/ListItem&gt;<br>          );<br>        })}<br>      &lt;/List&gt;<br>    &lt;/div&gt;<br>  );<br>}</pre><p>We just calculate totalLikeCount in the render scope dynamically. We have the access to posts prop and component gets re-rendered when posts prop is changed. So, why shouldn&#39;t we? We don&#39;t need to use any useState, useEffect or create a flow for deriving state here. We created a simpler code, prevented an unnecessary re-renders and just used what we need.</p><p>If there are a lot of items in the posts array and calculating totalLikeCount is time consuming, we can simply use useMemo as a performance optimization like:</p><pre>function getTotalLikeCount(posts) {<br>  let totalLikeCount = 0;<br>  posts.forEach((post) =&gt; {<br>    totalLikeCount = totalLikeCount + post.likeCount;<br>  });<br>  return totalLikeCount;<br>}</pre><pre>function PostList({ posts }) {<br>  const totalLikeCount = useMemo(() =&gt; {<br>    return getTotalLikeCount(posts);<br>  }, [posts]);</pre><pre>  return (<br>    &lt;div&gt;<br>      &lt;Title&gt;Posts&lt;/Title&gt;<br>      &lt;Subtitle&gt;Total Likes: {totalLikeCount}&lt;/Subtitle&gt;<br>      &lt;List&gt;<br>        {posts.map((post) =&gt; {<br>          return (<br>            &lt;ListItem key={post.id}&gt;<br>              &lt;PostAuthor author={post.author} /&gt;<br>              &lt;PostDate&gt;{post.createdAt}&lt;/PostDate&gt;<br>              &lt;PostBody&gt;{post.body}&lt;/PostBody&gt;<br>              &lt;Actions&gt;<br>                &lt;LikeButton postId={post.id} likeCount={post.likeCount} /&gt;<br>              &lt;/Actions&gt;<br>            &lt;/ListItem&gt;<br>          );<br>        })}<br>      &lt;/List&gt;<br>    &lt;/div&gt;<br>  );<br>}</pre><p>In summary, we need to check our requirements and use cases when we want to calculate/derive something based on props or some state and think about if we really need to make it a new state. We can use different approaches based on what we are gonna do with that derived value and how it should behave. In the end, you will see you have a much cleaner architecture and it will be much easier to maintain it in the long term.</p><p>Thanks for reading!</p><p><em>Originally published at </em><a href="https://onderonur.netlify.app/blog/how-to-calculate-values-based-on-props-or-state-in-react/"><em>https://onderonur.netlify.app</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=df27d642bbd3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Create Glowing Images with React]]></title>
            <link>https://onderonur.medium.com/how-to-create-glowing-images-with-react-cb66c1483cc2?source=rss-c091e96bb961------2</link>
            <guid isPermaLink="false">https://medium.com/p/cb66c1483cc2</guid>
            <category><![CDATA[css]]></category>
            <category><![CDATA[glowing-images]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[front-end-development]]></category>
            <category><![CDATA[styled-components]]></category>
            <dc:creator><![CDATA[Onur Önder]]></dc:creator>
            <pubDate>Mon, 18 Apr 2022 22:49:04 GMT</pubDate>
            <atom:updated>2022-04-20T18:40:58.447Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/680/0*GA7pQDYbr_6NqMdD.jpg" /><figcaption>Photo by <a href="https://unsplash.com/@nervum?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Jack B</a> on <a href="https://unsplash.com/s/photos/glow?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>First of all, even though this tutorial is based on React and styled-components, you can apply the same technique with any library/framework or just HTML and CSS.</p><h3>Preparing the Template</h3><p>Let’s run the following command to create a new React app:</p><pre>npx create-react-app@latest glowing-images</pre><p>After the installation is done and our project is created, we can open it and install our dependencies.</p><pre>npm install styled-components</pre><p>Now, we can delete all the files under src except index.js and App.js and set them like these:</p><pre>// src/index.js<br>import React from &#39;react&#39;;<br>import ReactDOM from &#39;react-dom/client&#39;;<br>import App from &#39;./App&#39;;</pre><pre>const root = ReactDOM.createRoot(document.getElementById(&#39;root&#39;));<br>root.render(<br>  &lt;React.StrictMode&gt;<br>    &lt;App /&gt;<br>  &lt;/React.StrictMode&gt;,<br>);</pre><pre>// src/App.js<br>function App() {<br>  return &lt;div&gt;&lt;/div&gt;;<br>}</pre><pre>export default App;</pre><p>Now, our template is ready and we can start creating our glowing images.</p><h3>Glowing Images</h3><p>Let’s apply the global styles first to override default browser stylings and also apply a dark background to make the glow effect more visible.</p><pre>// src/GlobalStyle.js<br>import { createGlobalStyle } from &#39;styled-components&#39;;</pre><pre>const GlobalStyle = createGlobalStyle`<br>    * {<br>      box-sizing: border-box;<br>      margin: 0;<br>      padding: 0;<br>    }</pre><pre>    body {<br>      padding: 0.8rem;<br>      background: #19222D<br>    }<br>`;</pre><pre>export default GlobalStyle;</pre><p>We import and use these styles in our app like:</p><pre>// src/App.js<br>import GlobalStyle from &#39;./GlobalStyle&#39;;</pre><pre>function App() {<br>  return (<br>    &lt;div&gt;<br>      &lt;GlobalStyle /&gt;<br>    &lt;/div&gt;<br>  );<br>}</pre><pre>export default App;</pre><p>Let’s start creating GlowingImage component to render our images.</p><pre>// src/GlowingImage.js<br>import styled from &#39;styled-components&#39;;</pre><pre>const GlowingImageRoot = styled.div`<br>  &gt; img {<br>    width: 100%;<br>    object-fit: cover;<br>    border-radius: inherit;<br>  }`;</pre><pre>function GlowingImage({ src, alt }) {<br>  return (<br>    &lt;GlowingImageRoot src={src}&gt;<br>      &lt;img src={src} alt={alt} /&gt;<br>    &lt;/GlowingImageRoot&gt;<br>  );<br>}</pre><pre>export default GlowingImage;</pre><p>We will use <a href="https://picsum.photos/">Picsum</a> to get random images.<br> Let’s display the image by centering it horizontally in our app:</p><pre>// src/App.js<br>import GlobalStyle from &quot;./GlobalStyle&quot;;<br>import GlowingImage from &quot;./GlowingImage&quot;;<br>import styled from &quot;styled-components&quot;;</pre><pre>const MainContent = styled.div`<br>  max-width: 24rem;<br>  margin: auto;<br>  padding: 1rem;<br>`;</pre><pre>function App() {<br>  return (<br>    &lt;div&gt;<br>      &lt;GlobalStyle /&gt;<br>      &lt;MainContent&gt;<br>        &lt;GlowingImage<br>          src=&quot;https://picsum.photos/230/345?random=0&quot;<br>          alt=&quot;Glowing Image&quot;<br>        /&gt;<br>      &lt;/MainContent&gt;<br>    &lt;/div&gt;<br>  );<br>}</pre><pre>export default App;</pre><p>It should look like this now:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/755/1*oCoatZF5ZVeMBtRtQVMouw.jpeg" /></figure><p>Now we need to add the glow effect. As you can guess, we will use GlowingImageRoot to add the stylings.</p><p>We will create a pseudo element by using :before and set its background image as same as our image. By doing this, we will have two layers of the same image on top of each other.</p><p>We also set border-radius and make img to inherit it to have a little rounded image.</p><pre>// src/GlowingImage.js<br>import styled from &#39;styled-components&#39;;</pre><pre>const GlowingImageRoot = styled.div`<br>  position: relative;<br>  border-radius: 0.6rem;</pre><pre>  &amp;:before {<br>    content: &quot;&quot;;<br>    position: absolute;<br>    inset: 0;<br>    background: ${({ src }) =&gt; `url(https://medium.com/$%7Bsrc%7D)`};<br>    background-size: cover;<br>    background-position: center;<br>    background-repeat: no-repeat;<br>    z-index: -1;<br>    border-radius: inherit;<br>  }</pre><pre>  &gt; img {<br>    width: 100%;<br>    object-fit: cover;<br>    border-radius: inherit;<br>  }<br>`;</pre><pre>function GlowingImage({ src, alt }) {<br>  return (<br>    &lt;GlowingImageRoot src={src}&gt;<br>      &lt;img src={src} alt={alt} /&gt;<br>    &lt;/GlowingImageRoot&gt;<br>  );<br>}</pre><pre>export default GlowingImage;</pre><p>Now, we can apply stylings to the background image, without affecting the original one.</p><p>To imitate a glow effect, we will add some blur to the background image and give it a little saturation to make its colors sharper.</p><pre>// src/GlowingImage.js<br>import styled from &#39;styled-components&#39;;</pre><pre>const GlowingImageRoot = styled.div`<br>  position: relative;<br>  border-radius: 0.6rem;</pre><pre>  &amp;:before {<br>    content: &quot;&quot;;<br>    position: absolute;<br>    inset: 0;<br>    background: ${({ src }) =&gt; `url(https://medium.com/$%7Bsrc%7D)`};<br>    background-size: cover;<br>    background-position: center;<br>    background-repeat: no-repeat;<br>    z-index: -1;<br>    border-radius: inherit;<br>    /* You can change these values until it looks fine to you */<br>    filter: blur(0.6rem) saturate(3);<br>  }</pre><pre>  &gt; img {<br>    width: 100%;<br>    object-fit: cover;<br>    border-radius: inherit;<br>  }<br>`;</pre><pre>function GlowingImage({ src, alt }) {<br>  return (<br>    &lt;GlowingImageRoot src={src}&gt;<br>      &lt;img src={src} alt={alt} /&gt;<br>    &lt;/GlowingImageRoot&gt;<br>  );<br>}</pre><pre>export default GlowingImage;</pre><p>We have a subtle glow now!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/755/1*sJU8x85SXTqngFeeUXzUbw.jpeg" /></figure><p>To make it more visible, we can apply some scaling too. We can make the background image bigger by scaling it up, but I prefer making the original image slightly smaller like:</p><pre>// src/GlowingImage.js<br>import styled from &#39;styled-components&#39;;</pre><pre>const GlowingImageRoot = styled.div`<br>  position: relative;<br>  border-radius: 0.6rem;</pre><pre>  &amp;:before {<br>    content: &#39;&#39;;<br>    position: absolute;<br>    inset: 0;<br>    background: ${({ src }) =&gt; `url(https://medium.com/$%7Bsrc%7D)`};<br>    background-size: cover;<br>    background-position: center;<br>    background-repeat: no-repeat;<br>    z-index: -1;<br>    border-radius: inherit;<br>    /* You can change these values until it looks fine to you */<br>    filter: blur(0.6rem) saturate(3);<br>  }</pre><pre>  &gt; img {<br>    width: 100%;<br>    object-fit: cover;<br>    border-radius: inherit;<br>    transform: scale(0.98);<br>  }<br>`;</pre><pre>function GlowingImage({ src, alt }) {<br>  return (<br>    &lt;GlowingImageRoot src={src}&gt;<br>      &lt;img src={src} alt={alt} /&gt;<br>    &lt;/GlowingImageRoot&gt;<br>  );<br>}</pre><pre>export default GlowingImage;</pre><p>And it’s done!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/755/1*Yaw4J7K8VBVceXiheoXmNA.jpeg" /></figure><p>To better understand this technique, we can make the original image non-visible temporarily and reveal our glowing image trick like:</p><pre>// src/GlowingImage.js<br>import styled from &#39;styled-components&#39;;</pre><pre>const GlowingImageRoot = styled.div`<br>  position: relative;<br>  border-radius: 0.6rem;</pre><pre>  &amp;:before {<br>    content: &#39;&#39;;<br>    position: absolute;<br>    inset: 0;<br>    background: ${({ src }) =&gt; `url(https://medium.com/$%7Bsrc%7D)`};<br>    background-size: cover;<br>    background-position: center;<br>    background-repeat: no-repeat;<br>    z-index: -1;<br>    border-radius: inherit;<br>    /* You can change these values until it looks fine to you */<br>    filter: blur(0.6rem) saturate(3);<br>  }</pre><pre>  &gt; img {<br>    width: 100%;<br>    object-fit: cover;<br>    border-radius: inherit;<br>    transform: scale(0.98);<br>    opacity: 0;<br>  }<br>`;</pre><pre>function GlowingImage({ src, alt }) {<br>  return (<br>    &lt;GlowingImageRoot src={src}&gt;<br>      &lt;img src={src} alt={alt} /&gt;<br>    &lt;/GlowingImageRoot&gt;<br>  );<br>}</pre><pre>export default GlowingImage;</pre><p>If you want, you can also add some hover animation to the glow effect like:</p><pre>// src/GlowingImage.js<br>import styled, { keyframes } from &#39;styled-components&#39;;</pre><pre>const glow = keyframes`<br>  from {<br>    transform: scale(1);<br>  }</pre><pre>  to {<br>    transform: scale(0.98);<br>  }<br>`;</pre><pre>const GlowingImageRoot = styled.div`<br>  position: relative;<br>  border-radius: 0.6rem;</pre><pre>  &amp;:before {<br>    content: &#39;&#39;;<br>    position: absolute;<br>    inset: 0;<br>    background: ${({ src }) =&gt; `url(https://medium.com/$%7Bsrc%7D)`};<br>    background-size: cover;<br>    background-position: center;<br>    background-repeat: no-repeat;<br>    z-index: -1;<br>    border-radius: inherit;<br>    /* You can change these values until it looks fine to you */<br>    filter: blur(0.6rem) saturate(3);<br>  }</pre><pre>  &amp;:hover {<br>    &amp;:before {<br>      animation: ${glow} 500ms ease-in-out alternate infinite;<br>    }<br>  }</pre><pre>  &gt; img {<br>    width: 100%;<br>    object-fit: cover;<br>    border-radius: inherit;<br>    transform: scale(0.98);<br>  }<br>`;</pre><pre>function GlowingImage({ src, alt }) {<br>  return (<br>    &lt;GlowingImageRoot src={src}&gt;<br>      &lt;img src={src} alt={alt} /&gt;<br>    &lt;/GlowingImageRoot&gt;<br>  );<br>}</pre><pre>export default GlowingImage;</pre><h3>Demo</h3><p>You can check the live demo on <a href="https://codesandbox.io/s/xnui7d">CodeSandbox</a>.</p><p>Thanks for reading!</p><p><em>Originally published at </em><a href="https://onderonur.netlify.app/blog/how-to-create-glowing-images-with-react/"><em>https://onderonur.netlify.app</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cb66c1483cc2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Sorting Arrays in JavaScript]]></title>
            <link>https://onderonur.medium.com/sorting-arrays-in-javascript-e9a334e36e9a?source=rss-c091e96bb961------2</link>
            <guid isPermaLink="false">https://medium.com/p/e9a334e36e9a</guid>
            <category><![CDATA[sorting]]></category>
            <category><![CDATA[arrays]]></category>
            <category><![CDATA[array-methods]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Onur Önder]]></dc:creator>
            <pubDate>Sun, 13 Dec 2020 16:31:41 GMT</pubDate>
            <atom:updated>2022-04-20T18:41:52.511Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/680/0*t-eJiRDUe_sEpDoC.jpg" /><figcaption>Photo by <a href="https://unsplash.com/@tolga__?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Tolga Ulkan</a> on <a href="https://unsplash.com/?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>JavaScript can be tricky sometimes. We know the times when we try something so easy like sorting an array, but it ends up so wrong and breaks our code.</p><p>When we know why this happens and how to fix it, it’s all easy actually.</p><h3>Array.sort()</h3><p>In JavaScript, arrays have an useful sort method and it can be used like this:</p><pre>const arr = [5, 7, 1, 3];<br>arr.sort();<br>console.log(arr);<br>// logs: [ 1, 3, 5, 7 ]</pre><p>Just as we expected, right? It sorts the array in an ascending order.</p><p>Let’s look at another example:</p><pre>const arr = [15, 17, 1, 2, 3];<br>arr.sort();<br>console.log(arr);<br>// logs: [ 1, 15, 17, 2, 3 ]</pre><p>And welcome to lands of JavaScript! You can try this code snippet and see if the result is right or wrong. But it’s absolutely right and there is a reason behind it.</p><p>The default method converts each of the elements to string and then compares them. So, even if we try this on an array full of numeric values, it ends up like this.</p><h3>The Compare function</h3><p>To make sort method to act as we want, we need to give it a compare function. It&#39;s an optional parameter, but we saw how it executes if we don&#39;t pass it. The function should look like this:</p><pre>function compare(firstItem, secondItem) {  <br>  // do things, and return a numeric value.<br>}</pre><p>Our compare function should return a numeric value after comparing two items.</p><ul><li>If it returns 0, order of compared values does not change.</li><li>If it returns a positive number, secondItem gets placed after firstItem.</li><li>If it returns a negative number, firstItem gets placed after secondItem.</li></ul><p>So, if we want our numeric values to be sorted in an ascending order, we can do it like this:</p><pre>function compareNumbers(firstItem, secondItem) {  <br>  return firstItem - secondItem;<br>}</pre><pre>const arr = [15, 17, 1, 2, 3];<br>arr.sort(compareNumbers);<br>console.log(arr);<br>// logs: [ 1, 2, 3, 15, 17 ]</pre><p>And that’s all we need to do! If we want to sort them in a descending order:</p><pre>function compareNumbersInReverse(firstItem, secondItem) {  <br>  return secondItem - firstItem;<br>}</pre><pre>const arr = [15, 17, 1, 2, 3];<br>arr.sort(compareNumbersInReverse);<br>console.log(arr);<br>// logs: [ 17, 15, 3, 2, 1 ]</pre><pre>// Or we can do it like this too<br>function compareNumbers(firstItem, secondItem) {  <br>  return firstItem - secondItem;<br>}</pre><pre>arr.sort(compareNumbers).reverse();<br>console.log(arr);<br>// logs: [ 17, 15, 3, 2, 1 ]</pre><h3>Sorting different data types</h3><p>We saw how we can sort numeric values. But what about other things?</p><h3>Date</h3><p>Using the firstItem - secondItem method is OK for Date objects too. If our object has a valueOf method that returns a numeric value and if it can indicate some sort of an order for that object, we can use this technique. For Date, its valueOf method returns number of milliseconds since the epoch (1970-01-01T00:00:00Z). So, we can use it to sort Date objects.</p><pre>function compareDates(firstDate, secondDate) {  <br>  return firstDate - secondDate;<br>}</pre><pre>const datesArr = [  <br>  new Date(2020, 0, 1),  <br>  new Date(2019, 5, 9),  <br>  new Date(2020, 6, 10),<br>];</pre><pre>datesArr.sort(compareDates);<br>console.log(datesArr);<br>// logs:<br>// [<br>//   2019-06-09T00:00:00.000Z,<br>//   2020-01-01T00:00:00.000Z,<br>//   2020-07-10T00:00:00.000Z<br>// ]</pre><p>Or we can use getTime method to be more explicit of course.</p><pre>function compareDates(firstDate, secondDate) {  <br>  return firstDate.getTime() - secondDate.getTime();<br>}</pre><h3>string</h3><p>We know that sort method implicitly converts items to string and compares them. So, why do we think about string values if we already have this? Let&#39;s have a look:</p><pre>const users = [&#39;User 1&#39;, &#39;User 5&#39;, &#39;User 30&#39;, &#39;User 12&#39;, &#39;User 18&#39;];<br>users.sort();<br>console.log(users);<br>// logs: [ &#39;User 1&#39;, &#39;User 12&#39;, &#39;User 18&#39;, &#39;User 30&#39;, &#39;User 5&#39; ]</pre><p>If we have numeric values in our strings and want to order items by considering them too, the default compare function is not enough for us.</p><p>For this case, we need to use <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/Collator">Intl.Collator</a>. It is a constructor that creates objects to be used in language sensitive string comparison.</p><pre>const collator = new Intl.Collator(undefined, {  <br>  // To consider numeric values in strings  <br>  numeric: true,<br>});<br>const users = [&#39;User 1&#39;, &#39;User 5&#39;, &#39;User 30&#39;, &#39;User 12&#39;, &#39;User 18&#39;];<br>users.sort(collator.compare);<br>console.log(users);<br>// logs: [ &#39;User 1&#39;, &#39;User 5&#39;, &#39;User 12&#39;, &#39;User 18&#39;, &#39;User 30&#39; ]</pre><p><em>As a side note, if we have a big array to sort, it’s better to use </em><em>Intl.Collator in terms of performance.</em></p><p>Also, the same thing can be achieved by using localeCompare too. It gets the same parameters as Intl.Collator constructor.</p><pre>function compareStrings(firstString, secondString) {  <br>  return firstString.localeCompare(secondString, undefined, { <br>    numeric: true,  <br>  });<br>}<br>const users = [&#39;User 1&#39;, &#39;User 5&#39;, &#39;User 30&#39;, &#39;User 12&#39;, &#39;User 18&#39;];<br>users.sort(compareStrings);<br>console.log(users);<br>// logs: [ &#39;User 1&#39;, &#39;User 5&#39;, &#39;User 12&#39;, &#39;User 18&#39;, &#39;User 30&#39; ]</pre><h3>Custom objects</h3><p>As we can see, we can compare items in an array as we want. So, comparing custom objects (or class instances etc.) are no different.</p><pre>function compareBeatles(firstBeatle, secondBeatle) {  <br>  return firstBeatle.age - secondBeatle.age;<br>}</pre><pre>const beatles = [  <br>  { name: &#39;John&#39;, age: 25 },  <br>  { name: &#39;Ringo&#39;, age: 28 },  <br>  { name: &#39;Paul&#39;, age: 26 },  <br>  { name: &#39;George&#39;, age: 25 },<br>];</pre><pre>beatles.sort(compareBeatles);<br>console.log(beatles);<br>// logs:<br>// [<br>//   { name: &#39;John&#39;, age: 25 },<br>//   { name: &#39;George&#39;, age: 25 },<br>//   { name: &#39;Paul&#39;, age: 26 },<br>//   { name: &#39;Ringo&#39;, age: 28 }<br>// ]</pre><p>And we can use custom methods of our object, of course.</p><pre>const dayjs = require(&#39;dayjs&#39;);</pre><pre>function compare(first, second) {  <br>  return first.diff(second);<br>}</pre><pre>const arr = [dayjs(&#39;2020-1-6&#39;), dayjs(&#39;2019-5-9&#39;), dayjs(&#39;2020-10-12&#39;)];</pre><pre>arr.sort(compare);<br>console.log(arr.map((date) =&gt; date.format(&#39;YYYY-MM-DD&#39;)));<br>// logs: [ &#39;2019-05-09&#39;, &#39;2020-01-06&#39;, &#39;2020-10-12&#39; ]</pre><h3>Array.sort() Mutates the Original Array</h3><p>Throughout our examples, you may have noticed something. We used sort method a lot, but never assigned the value returned from it. Yep, you knew it. It mutates the original array. So if we use this method in a project built with a package that doesn&#39;t want you to mutate data (like React, React-Native, Redux etc.), we need to consider this too. Even though it returns the mutated array as a result like:</p><pre>const sortedArr = arr.sort();</pre><p>it mutates the original.</p><p>To handle this, we can do something like:</p><pre>function sortNumbers(numberArr) {  <br>  // We use spread operator (...) to create a shallow copy of  <br>  // our original array. So, we don&#39;t mutate the original.  <br>  const sortedArr = [...numberArr].sort((first, second) =&gt; {<br>    return first - second;  <br>  });  <br>  return sortedArr;<br>}</pre><pre>let arr = [15, 17, 1, 2, 3];<br>arr = sortNumbers(arr);<br>console.log(arr);<br>// logs: [ 1, 2, 3, 15, 17 ]</pre><h3>Conclusion</h3><p>sort is a very cool method of Array class. When we know how it behaves on certain conditions, it&#39;s a really helpful method.</p><p>Thanks for reading!</p><p><em>Originally published at </em><a href="https://onderonur.netlify.app/blog/sorting-arrays-in-javascript/"><em>https://onderonur.netlify.app</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e9a334e36e9a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[State Management and Performance Optimization for React Context API with Hooks]]></title>
            <link>https://onderonur.medium.com/state-management-and-performance-optimization-for-react-context-api-with-hooks-dfc4c9d09f43?source=rss-c091e96bb961------2</link>
            <guid isPermaLink="false">https://medium.com/p/dfc4c9d09f43</guid>
            <category><![CDATA[react-native]]></category>
            <category><![CDATA[react-context-api]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[hooks]]></category>
            <category><![CDATA[react-hook]]></category>
            <dc:creator><![CDATA[Onur Önder]]></dc:creator>
            <pubDate>Sun, 15 Dec 2019 02:08:04 GMT</pubDate>
            <atom:updated>2021-12-09T09:26:40.759Z</atom:updated>
            <content:encoded><![CDATA[<h3>State Management and Performance Optimizations with React Context API and Hooks</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/758/1*ST54r7_l-6GfTrzFYGd0EQ.png" /></figure><p>State management for React applications is a concept with a lot of alternative solutions. We have things like <a href="https://redux.js.org/">redux</a>, <a href="https://mobx.js.org/README.html">mobx</a>, <a href="https://mobx-state-tree.js.org/intro/philosophy">mobx-state-tree</a>, <a href="https://www.apollographql.com/docs/react/">apollo-client</a> and many more. They all have many different and similar approaches, learning curves, complexities and simplicities. They are very very useful for many situations. But I think, they add a lot of unnecessary layers for a lot of applications. Because, you already have a state management solution and it’s built-in to React. It’s React itself…</p><p>With good component composition, creating minimal and maintainable components, using Context API and hooks, you can easily manage your application state. It takes some time to get used to, but any other third party package would take at least the same amount of time.</p><p>That’s enough for the introduction. Now we will talk about Context API and some good approaches to improve its performance.</p><h4>Enter the Counter Application</h4><p>This will be the most basic type of application that you can create instantly. Now open your editor, run the terminal and just run this command;</p><pre>npx create-react-app counter-app</pre><p>Give some time to CRA to create your project. When it’s done, delete all the files under the src folder and create the following files.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4b6d2d65f627e89a3e681346ea03b0e6/href">https://medium.com/media/4b6d2d65f627e89a3e681346ea03b0e6/href</a></iframe><p>This is just a simple counter. Nothing fancy. Just create the files those are in the snippets and run</p><pre>npm start</pre><p>The result should look like this.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/985/1*yPQdyMREUU45OUV1f2PQ4g.png" /></figure><p>Click the buttons and the count will be increased or decreased. Everything works as expected.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/986/1*hEi_LMhMxMuugSk8Hqh7Zg.png" /></figure><p>And also, we created a simple structure with Context and hooks to prevent prop drilling. We could do it the other way. It wouldn’t be hard for a simple application like this. But when you create real world applications, it can easily go unmaintainable.</p><p>But we have a giant problem and we are not aware of it yet. Look at the console output. Everytime you click one of the buttons, each of the components those are connected to the CounterContext just re-renders. We don’t see any slowness, but if we had more complex components, some animations etc. the application might be very very slow.</p><p>Each of the components are re-rendering, because they are connected to the CounterContext and we just update the context value everytime we click a button. Even if we just increase the count<strong> </strong>value, it is just a property under the value<strong> </strong>object and when we change it, its parent (value<strong> </strong>object itself) gets updated too. You can read about immutability and mutations in JavaScript to deeply understand this situation. Shortly, because of the context value is changed, every component that is using the context re-renders.</p><p>Here are some ways to overcome this.</p><h4>1. Using React.memo</h4><p>React.memo creates a memoized component and prevents unnecessary re-renders. So, if every prop and state of a component has the same value as the last time, it just doesn’t let the component to re-render.</p><p>The context value gets updated, but the increase and decrease functions still have the same memory reference (thanks to useCallbak<strong> </strong>hook). We just need to wrap our context consuming components with React.memo<strong>, </strong>remove their <strong>direct</strong> connection to the context, create a Counter component which is connected to the context and pass the required values as props to each component. With this pattern, we can prevent unnecessary re-renders. Let’s update these files;</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d1027a991a41242a854517df615bf55b/href">https://medium.com/media/d1027a991a41242a854517df615bf55b/href</a></iframe><p>Now click the buttons a few times and look at the console output again;</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/983/1*HP8CwUMD7FBFdHwcJm4yOg.png" /></figure><p>Only the Count component is re-rendering and this is exactly what we wanted. Nice!</p><h4>2. Separate Contexts</h4><p>Another approach is separating the context into multiple parts and providers. The only changing part of our context is the count. increase<strong> </strong>and decrease remains the same. So, if a component only wants one or both of these functions and doesn’t care about count value, it doesn’t need to know about the update too. Now, we will divide our context into 2 parts. CountContext and CountActionsContext . Let’s see the updated files;</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6d0ae70e69fcb1960367371988428579/href">https://medium.com/media/6d0ae70e69fcb1960367371988428579/href</a></iframe><p>Now, we don’t need to use React.memo with every context connected component. We just need to use it with Count. Because, each time the count state is updated, App component re-renders and it triggers its children to re-render too. Because that the CountProvider and CountActionsProvider has a children prop, they can’t be memoized with React.memo. Because the children will be created from scratch each time. They will not have the same memory reference, so the shallow equality comparison of provider props will fail. By putting the Count component in React.memo, we ensure that even if the App, CountProvider and CountActionsProvider re-rendered, Count and its children will not re-render unnecessarily.</p><p>Let’s click the buttons and look at the console output again;</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/985/1*oV5X7dFHyhKhuRo5pwLrVg.png" /></figure><p>We have the exact same output as the first performance optimization option. Cool!</p><h4>3. Using constate</h4><p><a href="https://github.com/diegohaz/constate">constate </a>is a simple package to split your context value into multiple pieces. If you look at the source code of it, you will notice it’s just a few lines of code, but it is a smart design!</p><p>constate simply splits the context value with the functions you give it and creates multiple nested providers. So, if you want to use a part of the context value, you simply use the context and the hook dedicated to that part.</p><p>If you’re familiar with the selectors of redux this feels like them. We are simply <em>selecting</em> some part of the context value.</p><p>Now run this command to install the package.</p><pre>npm install constate</pre><p>Let’s see the updated files;</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f00abf0851310e529faa938804863f6f/href">https://medium.com/media/f00abf0851310e529faa938804863f6f/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/983/1*FJOtLJjbJn1ChLlhKR6lUA.png" /></figure><p>Exactly the same output as the other two options.</p><h4>Conclusion</h4><p>These three options are valid and makes your application to run smoothly. You can create your own patterns while considering the requirements of your application.</p><p>Personally, I like <strong>constate</strong> the most. If I wouldn’t use it directly (it also uses TypeScript, has a medium sized community and unit tests, so why not?), I would just look at its source code and customize it to my needs. It removes a lot of effort and code from the project.</p><p>Separating context into multiple parts is a little bit verbose, while it’s the currently recommended way by the React team.</p><p>Just using React.memo and optimizing Context may be a little bit less verbose, but it may cause <em>prop drilling </em>if you don’t compose components in a proper way. So, it depends…</p><p>Thanks for reading!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=dfc4c9d09f43" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>