<?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 Aditya Kumar on Medium]]></title>
        <description><![CDATA[Stories by Aditya Kumar on Medium]]></description>
        <link>https://medium.com/@adii.utsav?source=rss-f1d05be749b2------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*xxgf-w1iGvaOi8T8keSruw.jpeg</url>
            <title>Stories by Aditya Kumar on Medium</title>
            <link>https://medium.com/@adii.utsav?source=rss-f1d05be749b2------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 17 Nov 2026 09:51:47 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@adii.utsav/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[ReactJS — Part 8]]></title>
            <link>https://medium.com/@adii.utsav/reactjs-part-8-bfd20dc159c5?source=rss-f1d05be749b2------2</link>
            <guid isPermaLink="false">https://medium.com/p/bfd20dc159c5</guid>
            <category><![CDATA[zustand]]></category>
            <category><![CDATA[front-end-development]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[reactjs]]></category>
            <dc:creator><![CDATA[Aditya Kumar]]></dc:creator>
            <pubDate>Sat, 01 Aug 2026 02:16:01 GMT</pubDate>
            <atom:updated>2026-08-01T02:16:01.559Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/875/0*w3wazGPCRfCgu5Mc.jpeg" /></figure><p><strong>Zustand:</strong></p><p><strong>What is Zustand?</strong></p><p>Zustand is a small, lightweight state management library for React. Its purpose is to let multiple components share state without prop drilling or excessive Context providers.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/550/1*ugYRX1VgyBJS4ZLcyezLmA.png" /></figure><p><strong>How to install Zustand?</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*TErtB37A3xaNNUmuLRJAIQ.png" /></figure><p>Let’s first create the store in zustand:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*u1Vj_xRhdWAX9ImYye_wnw.png" /></figure><p>This code creates a <strong>global store</strong> using Zustand to manage a list of courses in a React app. It starts with an empty courses array and provides functions to add a course, remove a course, and toggle a course’s completion status by updating the shared state with set(). The persist middleware saves the course data in the browser’s local storage, so it remains available after a page refresh, while devtools lets you inspect and debug state changes using the Redux DevTools browser extension. Finally, the store is exported as useCourseStore, which any React component can use to access and update the shared course data.</p><p><strong>Note:</strong> The removeCourse and toggleCourseStatus functions contain a few coding mistakes and would need small fixes to work correctly.</p><p>Now, we will create the form to take the input and store in the ‘store’.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*wnnEfpD5qD74iWmK2MN2vg.png" /></figure><p>Updated courseStore.js:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*YBep2faAOhmhpL5-QotDxg.png" /></figure><p>Output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*Aa-KtzFSx6pURMjjEtfEWg.png" /></figure><p><strong>Contact Me</strong><br>📧 <strong>Email:</strong> adii.utsav@gmail.com<br>🔗 <strong>LinkedIn:</strong> <a href="https://www.linkedin.com/in/aditya-kumar-3241b6286/">https://www.linkedin.com/in/aditya-kumar-3241b6286/</a><br>💻 <strong>GitHub:</strong> <a href="https://github.com/Rememberful">https://github.com/Rememberful</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bfd20dc159c5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ReactJS — Part 7]]></title>
            <link>https://medium.com/@adii.utsav/reactjs-part-7-83f87fa10e15?source=rss-f1d05be749b2------2</link>
            <guid isPermaLink="false">https://medium.com/p/83f87fa10e15</guid>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[reactjs]]></category>
            <category><![CDATA[frontend-development]]></category>
            <category><![CDATA[mern-stack]]></category>
            <category><![CDATA[web-development]]></category>
            <dc:creator><![CDATA[Aditya Kumar]]></dc:creator>
            <pubDate>Fri, 31 Jul 2026 02:01:03 GMT</pubDate>
            <atom:updated>2026-07-31T02:01:03.045Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/875/0*HRif7vlipcE3WwT9.jpeg" /></figure><p><strong>React Hook Form:</strong></p><p><strong>What is React Hook Form?</strong></p><p>React Hook Form is a library for managing forms in React applications using React Hooks. It helps handle:</p><p>· Form state management</p><p>· Input registration</p><p>· Validation</p><p>· Error handling</p><p>· Form submission</p><p>while minimizing unnecessary re-renders, making forms faster and more performant than many traditional approaches.</p><p><strong>Why Use React Hook Form?</strong></p><p>1. Less code</p><p>2. Built-in Validation</p><p>3. Better Performance</p><p>4. Works well with Large Forms</p><p><strong>How to install it?</strong></p><p>Command:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/341/1*UNPbAWqcnXPWK6UzCeCdUA.png" /></figure><p>Now, let’s see an example using the code…!</p><p>App.jsx: a basic form.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/913/1*3otOabr0LZb5e91z4uLfLA.png" /></figure><p>This code creates a simple form in React using React Hook Form that collects a user’s first name, middle name, and last name. The useForm() hook is used to manage the form, and the register() function connects each input field to React Hook Form so it can track the values entered by the user without needing separate useState variables. When the user clicks the submit button, handleSubmit(onSubmit) gathers all the input values into a single object and passes it to the onSubmit function, which then logs the collected data to the console. For example, if the user enters “John”, “Michael”, and “Doe”, the console will show { firstName: “John”, middleName: “Michael”, lastName: “Doe” }. In short, this code demonstrates how React Hook Form simplifies form handling by automatically managing form data collection and submission with minimal code.</p><p>Output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/452/1*JxKNRd2UVLTEzz7XPobbcA.png" /></figure><p>Output: when filled and clicked on the submit button.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*i06tsmL1V7fYG0-88pv7kA.png" /></figure><p>Now, let’s talk about the validation, and restriction. Suppose I want that the first name shall be mandatory and its minimum length be 3.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/882/1*nyrnff2Krv2bQlT1ecEAcg.png" /></figure><p>Output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/559/1*gdUGsseOnJfci1rjEZDBow.png" /></figure><p>Output: it will allow the submit only when this condition is met (condition of required field, minimum length)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*jkGUSaPhMQZUbxkSpMikaw.png" /></figure><p>Now, we can also add some error message for the case the validation is not met. How?</p><p>App.jsx:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/912/1*Jg3WxaVltVCU9bGPAXiV1w.png" /></figure><p>Output: when I try to submit with two characters only.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/604/1*eeCpbDdkB0CXYNVrlvhnHQ.png" /></figure><p><strong>Rules for ReactJS Hook:</strong></p><p>The Rules of Hooks in React ensure that hooks work consistently and correctly.</p><p>1. Only Call Hooks at the Top Level</p><p>2. Only Call Hooks from React Functions</p><p>3. Custom Hook Names Must Start with use</p><p>4. Follow the Dependency Rules for Effects</p><p><strong>Note:</strong> A custom hook can use React’s built-in hooks (useState, useEffect, etc.), and a custom hook can also call another custom hook.</p><p><strong>Custom Hooks:</strong></p><p>Custom Hooks are reusable JavaScript functions that let you share stateful logic between React components. Their names must start with use.</p><p>Benefits: Reusability, cleaner components, and separation of logic from UI.</p><p>A custom hook:</p><p>· Starts with the word use</p><p>· Can use other React hooks (useState, useEffect, useContext, etc.)</p><p>· Can call other custom hooks</p><p>· Returns values, functions, or objects that components can use</p><p>Syntax:</p><p><em>function useCustomHook() {</em></p><p><em>// Hook logic</em></p><p><em>return value;</em></p><p><em>}</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/705/1*W3K-Z01A9mM2bhrOq2CSig.png" /></figure><p>Also,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/693/1*K6ey3e4TEHDGVdpBc0L0yA.png" /></figure><p>Example: a basic custom hook, useToggle, to hide and show the text.</p><p>App.jsx:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/743/1*5m5MyhCsVSR8Lre19_mLAg.png" /></figure><p>useToggle.jsx:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/841/1*IdOVC5OMZ2t0ezy4XkIqbQ.png" /></figure><p>Output: on load.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*xswP4k3ZsH5-PN7cYOi5Kg.png" /></figure><p>Output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*QT7c81H9rIwGxop8LSkyeA.png" /></figure><p>Output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*Yy7XV9ksCk4_hGN5V3uNuQ.png" /></figure><p><strong>API:</strong></p><p><strong>What is API?</strong></p><p>In React, an API (Application Programming Interface) is usually a way for your React application to communicate with a server or another application to get or send data.</p><p><strong>Common API Methods</strong></p><p>· <strong>GET</strong> — Retrieve data.</p><p>· <strong>POST</strong> — Create new data.</p><p>· <strong>PUT/PATCH</strong> — Update existing data.</p><p>· <strong>DELETE</strong> — Remove data.</p><p><strong>Popular Ways to Call APIs in React</strong></p><p>· Built-in fetch()</p><p>· <a href="https://axios-http.com/?utm_source=chatgpt.com">Axios</a> (popular HTTP client library)</p><p><strong>Simple Rule:</strong></p><p>· Browser JavaScript (React) usually needs APIs because it cannot safely access databases directly.</p><p>· Node.js can access databases directly, so it may not need another API.</p><p>· Both JavaScript and Node.js can call APIs when they need data from another service.</p><p>So, suppose if we have an API URL to work on, then first we will test if the API is working properly or not.</p><p>We can use POSTMAN, etc tools. But we are here using the Thunder Client extension provided in the VS code. The interface which opens:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*C3AqxMkTA4Tyy_8I88B9hw.png" /></figure><p>Now, just use the dummy API: <a href="https://dummyjson.com/users">https://dummyjson.com/users</a> . Simply paste it, and “GET” and then send the request.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*DPZnVbmmNqo_DEpjvHEw2w.png" /></figure><p>Now, we will see how to use it in code.</p><p>App.jsx:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/897/1*lT7OMKrs-MwHvFIomkyhow.png" /></figure><p>This React component uses useEffect() with an empty dependency array ([]) so that getUserData() runs only once when the component first loads. The getUserData() function is asynchronous; it uses fetch() to send a GET request to the DummyJSON users API, waits for the response, converts the returned JSON data into a JavaScript object using response.json(), and then prints the user data to the browser console.</p><p>Output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/845/1*zhVgvsjQVUfXViRUUtDUcA.png" /></figure><p>Also, you can see that there are coming some extra information such as the limit, skip, etc. in order to get only the users data. We can use useState and then use the response.users.</p><p>App.jsx:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*ZXAV108TTArS5lD-XfEocA.png" /></figure><p>This React component uses useState([]) to create a state variable called usersData, which initially stores an empty array. When the component loads for the first time, useEffect() calls the getUserData() function, which fetches user data from the API, converts the response from JSON into a JavaScript object, and then stores the users array from the response into the usersData state using setUsersData(). Updating the state causes React to re-render the component with the new data. The console.log(usersData) statement prints the current state to the console, so you’ll first see an empty array and then the fetched users after the API request completes.</p><p>Output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*oeAsGkE9tciMJN0G509qCA.png" /></figure><p>Now, suppose I want this data of console to render on the screen as well. Then we will use the ‘map’.</p><p>App.jsx:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*d07AyGX_Fu7-5dO2BT_BoA.png" /></figure><p>Output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/929/1*RC_E3fQSDHHGe33rjL2zfg.png" /></figure><p>This React component uses useState to store user data in the usersData state variable, which starts as an empty array. When the component first loads, useEffect calls the getUserData() function, which fetches user information from the DummyJSON API, converts the response into JSON, and saves the users array into state using setUsersData(). Updating the state causes React to re-render the component, and the map() function loops through each user in usersData, displaying their first and last names inside a list. The key={user.id} helps React efficiently track and update each list item.</p><p><strong>JSON server:</strong></p><p><strong>What is JSON?</strong></p><p>JSON (JavaScript Object Notation) is a lightweight format used to store and exchange data between applications.</p><p>Example:</p><p><em>{<br> “id”: 1,<br> “name”: “Rahul”,<br> “email”: “rahul@example.com”<br> }</em></p><p><strong>Why JSON?</strong></p><p>JSON is commonly used in APIs because it is easy for both humans and programs to read.</p><p><strong>What is JSON Server?</strong></p><p>JSON Server is a tool that creates a fake REST API from a JSON file. Instead of building a backend using Node.js, Express, Java, PHP, etc., you can quickly create APIs for frontend development and testing.</p><p><strong>What is db.json?</strong></p><p>db.json is the database file used by JSON Server.</p><p><strong>How to install JSON server?</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*znzXKx-5Vt7fCoAyY4tYog.png" /></figure><p><strong>How to Run JSON Server?</strong></p><p>Open terminal in the project folder:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*RrgN00MszW6sg9O1zUf6oA.png" /></figure><p>Now, how to check if the APIs are there or not?</p><p>Copy-paste the local host link:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*ixETytNPUPPNIUS4pNw_Sw.png" /></figure><p>Click on any link:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*Fnlfg9U6Y7TE4YUIG5focw.png" /></figure><p>Yes, it worked. We can also test it in ThunderClient.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/781/1*Pjx2BeXc23STsTm4NQ2nkQ.png" /></figure><p>Now, how to make the API call? We can create the function for API call:</p><p>App.jsx: (we did the same in the API section)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1008/1*8owQrj4TZhhs0iDupbhmEA.png" /></figure><p>Output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*RjNoSWP_MYT78YPbFZE1xQ.png" /></figure><p>Now, we will render the content of the db.json on the screen, for this we will use the state and the map.</p><p>App.jsx:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*qKLwtHenFzWO-9MXYkxN5w.png" /></figure><p>Output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*VJJV6EwfM726vI7py_ZCRQ.png" /></figure><p>Now, adding the POST method in the code:</p><p>App.jsx:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*bzrxFU2wHvDEwpAxsfgoxQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*THOIOQXHaqiSZduSfeCQlw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*LYLODpNy_XzA7N2OuKtwHQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*naC50JL6UL22Dl-M3Lb--Q.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*sYN6v3JUlE74CiAjcaBmJw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*YhvqKWk6HAxoX4aRhjzV2A.png" /></figure><p>Now, the DELETE method:</p><p>App.jsx:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*l5fI6SlheVcnkNaKyVra_w.png" /></figure><p>This deletePost function sends a <strong>DELETE request</strong> to remove a specific post from the server. It creates the URL by appending the entered id to the /posts endpoint, so only that post is targeted (for example, /posts/2). The fetch() function sends the request with method: “DELETE”. After the request completes, response.ok checks whether the deletion was successful. If it is, the ID input field is cleared, getUserData() is called to refresh the list of posts so the deleted post disappears from the UI, and a success message is displayed. If the request fails, an error message is shown to inform the user.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*fT5ppfQZqPkorHM8JIfllQ.png" /></figure><p>Now, adding the PUT method to edit the posts the snippet:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*lha3NlKHXrG4goS8haHHtw.png" /></figure><p>Now, adding the PATCH:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*rAlAnvO76ym2QRYCO4dTSw.png" /></figure><p><strong>Contact Me</strong><br>📧 <strong>Email:</strong> adii.utsav@gmail.com<br>🔗 <strong>LinkedIn:</strong> <a href="https://www.linkedin.com/in/aditya-kumar-3241b6286/">https://www.linkedin.com/in/aditya-kumar-3241b6286/</a><br>💻 <strong>GitHub:</strong> <a href="https://github.com/Rememberful">https://github.com/Rememberful</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=83f87fa10e15" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ReactJS — Part 6]]></title>
            <link>https://medium.com/@adii.utsav/reactjs-part-6-86ca9f22cb6d?source=rss-f1d05be749b2------2</link>
            <guid isPermaLink="false">https://medium.com/p/86ca9f22cb6d</guid>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[front-end-development]]></category>
            <category><![CDATA[reactjs]]></category>
            <category><![CDATA[mern-stack]]></category>
            <dc:creator><![CDATA[Aditya Kumar]]></dc:creator>
            <pubDate>Tue, 28 Jul 2026 14:05:43 GMT</pubDate>
            <atom:updated>2026-07-28T14:05:43.557Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/875/0*z96d6OP5q2bUtBhw.jpeg" /></figure><p><strong>Redux:</strong></p><p><strong>What is Redux?</strong></p><p>· Redux is a state management library often used with React to handle and centralize application state in a predictable way.</p><p>· Redux is a central store for your application state. Instead of keeping state scattered across many components in React, Redux keeps everything in one place called the store.</p><p>So instead of:</p><p>· Component A managing some state</p><p>· Component B managing related state</p><p>· Passing props around everywhere</p><p>You get:</p><p>· One global state container</p><p>· Any component can access or update it</p><p><strong>Problems without Redux</strong></p><p>· Prop drilling (passing props through many layers)</p><p>· Hard to share state between distant components</p><p>· Multiple components updating same state in inconsistent ways</p><p>· Debugging becomes difficult</p><p>· State logic scattered everywhere</p><p><strong>Core Concepts of Redux: </strong>Redux is built on a few simple ideas:</p><p>1. Action</p><p>2. Reducer</p><p>3. Slice</p><p>4. Store</p><p>5. State</p><p><strong><em>Component → Action → Reducer/Slice → Store → State → Component updates</em></strong></p><p>Understanding the flow using the flow diagaram: here we are clicking on the button which has the onClick event which is triggering the function handleClick() which will increase the value of count.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*VKUUfNslTunnyMT9YDtELw.png" /></figure><p>Let’s understand each concept of redux in details one by one:</p><p><strong>What is an Action?</strong></p><p>· An action is a plain object describing an event.</p><p>· A description of <em>something that happened</em> in the app, along with any extra data required to process it.</p><p>· Action = Event(type-manadatory) + Data(additional info- optional) needed to handle that event</p><p><strong>What is Slice?</strong></p><p>· It is a combination of state + reducers + actions for a specific part of the application.</p><p>· It represents one “section” (or “feature”) of your global Redux store.</p><p>· A slice is a feature-based module in Redux that contains state, reducers, and automatically generated actions for a specific part of the store.</p><p>· Slice contains the following things: initial state (Starting data for that feature), reducers (Functions that describe how state changes) and name (Used to prefix action types).</p><p><strong>What is Reducer?</strong></p><p>· A function that decides how the state should change based on an action.</p><p>· A reducer must NOT modify the original state directly. Instead, it must return a new copy of state.</p><p>· UI → dispatch(action) → reducer → new state → UI updates</p><p>· A reducer is a pure function that takes the current state and an action, and returns the next state of the application.</p><p><strong>What is Store?</strong></p><p>· A store is the central object that holds and manages the entire Redux state of your application.</p><p>· Component → Action → Reducer/Slice → Store → State → Component updates</p><p>· It basically holds the state, then receives the actions, and passes it to appropriate reducers (it passes currentState and action), it then update the store with the new value returned from the Reducers, and then it notifies react to re-render.</p><p>· A store is the central Redux container that holds the application’s state, receives actions, runs reducers, and provides updated state to components.</p><p>Basically,</p><p>· <strong>Action</strong> → “What happened?”</p><p>· <strong>Reducer</strong> → “How should state change?”</p><p>· <strong>State</strong> → “Current data”</p><p>· <strong>Slice</strong> → “Feature-specific Redux logic” (Action + Reducer in RTK)</p><p>· <strong>Store</strong> → “The central place managing all state and reducers”</p><p>Example:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*m_emoyOWI7VTvsiEr1kv1A.png" /></figure><p>Redux data flow operates in a continuous, one-way cycle starting right from the user interface. It begins when a user clicks the “Increment Btn” on the UI, which originates an onClick event. This event triggers an event handler function called handleClick(). Inside this handler, the dispatch() function is called, sending a specific Action (in this case, the increment() action creator) toward the centralized Store. The Reducer function inside the store receives this action, processes the logic (count + 1), and uses it to perform the state transition. Once the reducer updates the state inside the Store (changing the count from 0 to 1), a UI Update is automatically triggered, pushing the newly updated state back to the frontend screen to change the displayed count value from 0 to 1.</p><p><strong>How to install redux toolkit?</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*O4Pjl9TH2eIRvPBoJZMXUg.png" /></figure><p>Also, install this as well:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*Rhrt90v1ySa6aMY2eLampg.png" /></figure><p>Now, let’s see an example:</p><p>We will start by creating the store:</p><p>Store.js:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/890/1*6v7d7sgkt83j8GuknOW_UA.png" /></figure><p>Now, wrapping the application using the Provider: we did it to make the store accessible across the entire application.</p><p>Main.jsx:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*OZbVT04KRAEkxLmUNuRLDg.png" /></figure><p>Now, we will create the slice: for this we created one folder in the src as features and inside it we created another folder named counter, and inside it we created the counterSlice.jsx.</p><p>CounterSlice.jsx:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/767/1*ObNck3CvHmFQwmv-LX5DVw.png" /></figure><p>Now, we will register the counter to the store:</p><p>Store.js:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*gRjbNr3u0tjI2Ss5dci6JQ.png" /></figure><p>Now, we will create the UI.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*LPg6TJrH-9fTd4icXpSftQ.png" /></figure><p>Output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*KwS11UIFjX6uC44gH7ZdpA.png" /></figure><p>Output: when + was clicked.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*a3NVqOwXOuoffqpv9nsUCA.png" /></figure><p>Output: when — was clicked.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*gFLh02hIamRAQe0IJlPH2A.png" /></figure><p><strong>State Lifting in React:</strong></p><p><strong>What is State lifting?</strong></p><p>· State lifting is a React pattern where state is moved from a child component to the closest common parent component so that multiple components can share and use the same data.</p><p>· State lifting in React is the process of moving state from a child component to its nearest common parent so that multiple components can share and stay synchronized with the same data. It creates a single source of truth and allows data to be passed down through props.</p><p><strong>When Should You Lift State Up?</strong></p><p>Lift state up when:</p><p>· Multiple components need the same data.</p><p>· One component updates data that another component displays.</p><p>· You want a single source of truth for the data.</p><p>Examples:</p><p>· Shopping cart count shown in multiple places.</p><p>· Search input and search results.</p><p>· Form fields whose values affect other components.</p><p>· Theme (dark/light mode) shared across components.</p><p>Now, let’s first see an example of passing data from parent to child, which is the normal thing.</p><p>App.jsx:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*F9RzPMkfWiKnFUT1o_bCIg.png" /></figure><p>Card.jsx:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*DhtQWMPzdQwinrJvH1OzpQ.png" /></figure><p>Output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/914/1*plXxJJgrajRtlZk7wTDfiw.png" /></figure><p>Now, to make this example as child to parent communication, we will make sure that we will be doing these things in the parent:</p><p>-&gt; Create state</p><p>-&gt; Manage state</p><p>-&gt; Change state</p><p>-&gt; Syncing state in all child</p><p>But how will we do this?</p><p>App.jsx:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*OwxIAsMwMguhtcV2iz1Rqw.png" /></figure><p>App.jsx is the parent component that stores and manages the name state using useState. It passes the setName function to the Card component, allowing the child to update the parent’s state whenever the user types in the input field. Whenever name changes, App re-renders and displays the latest value inside the &lt;p&gt; tag. In simple terms, App owns the data (name) and lets Card update it, which is an example of lifting state up in React.</p><p>Card.jsx:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*e22S87P8tQkVSppKShSVuQ.png" /></figure><p>Card.jsx is a child component that displays a text input box. It doesn’t store any data itself. Instead, whenever the user types something, it captures the input value and calls props.setName(e.target.value), which updates the name state stored in the parent component (App). In simple terms, Card collects the user’s input and sends it to the parent to be saved and managed.</p><p>Output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*r7Tme-ymU0rCHLGoBfHTdA.png" /></figure><p>Output: when we start typing.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*lC8hl01eNULW2r2uuchpoA.png" /></figure><p>How is this state lifting?</p><p>The state that is related to the input could have been kept inside Card, but instead it is “lifted up” and stored in App. The child (Card) updates the state, while the parent (App) owns and manages it. This process of moving state from a child to its parent is called state lifting (lifting state up).</p><p>Now, we can even pass the data among siblings, which is also an example of state lifting.</p><p>App.jsx:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*-4jhbJR_67Ckoug7vjFB_g.png" /></figure><p>DispalyUser.jsx:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/871/1*Tb2U58OMsQk6FYWWubvnAQ.png" /></figure><p>AddUser.jsx:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*ZalWJabOo_txfa12HnvTqA.png" /></figure><p>Output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/858/1*Nr5ReoDzk0NurUnUKMIm1w.png" /></figure><p><strong>Contact Me</strong><br>📧 <strong>Email:</strong> adii.utsav@gmail.com<br>🔗 <strong>LinkedIn:</strong> <a href="https://www.linkedin.com/in/aditya-kumar-3241b6286/">https://www.linkedin.com/in/aditya-kumar-3241b6286/</a><br>💻 <strong>GitHub:</strong> <a href="https://github.com/Rememberful">https://github.com/Rememberful</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=86ca9f22cb6d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ReactJS — Part 5]]></title>
            <link>https://medium.com/@adii.utsav/reactjs-part-5-df7daaf8aa57?source=rss-f1d05be749b2------2</link>
            <guid isPermaLink="false">https://medium.com/p/df7daaf8aa57</guid>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[front-end-development]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[mern-stack]]></category>
            <category><![CDATA[reactjs]]></category>
            <dc:creator><![CDATA[Aditya Kumar]]></dc:creator>
            <pubDate>Fri, 24 Jul 2026 08:52:19 GMT</pubDate>
            <atom:updated>2026-07-24T08:52:19.011Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/875/0*9wrfg-Qu4yI2kRFK.jpeg" /></figure><p><strong>useMemo Hook:</strong></p><p><strong>What is useMemo?</strong></p><p>useMemo is used to memoize (cache) the result of an expensive calculation so that React doesn’t recompute it on every render. useMemo remembers the result of a calculation and recalculates it only when its dependencies change.</p><p>Syntax:</p><p><em>const memoizedValue = useMemo(() =&gt; {<br> return someExpensiveCalculation();<br> }, [dependencies]);</em></p><p>· The function runs on the first render.</p><p>· It runs again only if one of the dependencies changes.</p><p>· Otherwise, React returns the cached value.</p><p>Now, let’s see a real example of expensive calculation: (not using useMemo)</p><p>Example:</p><p>App.jsx:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*BDZJ8HbnaqkITVD3TvzAHw.png" /></figure><p>Output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*aHZyillNGu4R2Euxp9asrg.png" /></figure><p>Output: when clicked on the button. The value of count will take some extra time now to increase.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/814/1*Iauy41eutSzYfvDcW2Swlg.png" /></figure><p>Example: doing the same thing using the useMemo hook.</p><p>App.jsx:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/891/1*6A_fvuLMOdHatarOi64uaA.png" /></figure><p>This component has two pieces of state: count and input. The expensiveTask() function simulates a slow calculation by looping many times and then returns input * 2. The useMemo hook caches the result of this calculation in doubleValue and only recalculates it when input changes. So, when you click the Increment button and only count changes, the component re-renders but expensiveTask() does not run again, improving performance by avoiding unnecessary expensive computations.</p><p>Output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*sT0ZMoHCG2n52MpP8Tl_RA.png" /></figure><p>Output: now count will increase quickly, while the double calculation will take time for sure.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/925/1*4PSen28DGyGZAuwAOuDpwg.png" /></figure><p>Another example of useMemo:</p><p>App.jsx:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*t7jZorlL8oIxx6DbKlUZXQ.png" /></figure><p>Output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*K1Gd8xgYzkkcF9c-dOtmXg.png" /></figure><p>Output: when Update count button was clicked multiple times. This is okay.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*1353w_zeCSJzaEjA0aWKWA.png" /></figure><p>Output: when update item is clicked. Clearly, it didn’t lead to change the console.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*p1BOJrAXp46fASnDaurUbQ.png" /></figure><p>Explanation: In this code, multiCountMemo is calculated using useMemo, which means React will only run the multiCount function again when count changes. So, when you click Update Count, count changes, multiCount runs again, and count * 5 is recalculated. However, when you click Update Item, only item changes, so React re-renders the component but does not execute multiCount again because count is still the same. If useMemo were not used and you simply wrote const multiCountMemo = count * 5 or called a function directly, then multiCount would run on every single re-render, including when only item changes. In this example the calculation is simple, so the performance difference is negligible, but for expensive computations useMemo helps avoid unnecessary recalculations and improves performance.</p><p><strong>useCallback Hook:</strong></p><p><strong>What is useCallback?</strong></p><p>useCallback is a built-in React Hook that lets you cache (memoize) a function definition between re-renders of a component.</p><p><strong>Syntax:<br> </strong><em>const cachedFn = useCallback(fn, dependencies)</em></p><p>· fn: The function value that you want to cache.</p><p>· dependencies: An array of reactive values (props, state, or variables derived from them) used inside the function. React will recreate the function <em>only</em> if one of these dependencies changes.</p><p><strong>Common Use Cases:</strong></p><p>You should reach for useCallback primarily in these scenarios:</p><p>1. Passing callbacks to optimized child components: As shown above, when a child component relies on shallow prop comparison (React.memo) to prevent useless renders.</p><p>2. Custom Hooks: If you are writing a custom Hook and returning a function, wrapping it in useCallback ensures consumers of your hook can safely use it in their own dependency arrays.</p><p>3. Function is a dependency elsewhere: If your function is passed into <em>another</em> hook’s dependency array (like a useEffect), omitting useCallback will cause that useEffect to run on every single render.</p><p>Basically,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*s3tbXmUW648rLVfmbIV26g.png" /></figure><p>Example: preventing the unnecessary re-rendering of child. But first see an example of unnecessary re-rendering of child.</p><p>App.jsx:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*V_WtYq_YDJIJ9lwDL60XWA.png" /></figure><p>ChildComponent.jsx:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*ppeyCnSFsTL7hSEgQlCVTA.png" /></figure><p>Output: when loaded.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*mKj8ZahvIAP6ruBQo2hZrw.png" /></figure><p>Output: when button increment button was clicked. Clearly, the number of times, the re-rendering happens the number of times, the ChildComponent get re-rendered.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*sq4LbKeiEJ_NcUXawsDlZA.png" /></figure><p>What happens when you click Increment?</p><p>1. setCount(count + 1) updates the state.</p><p>2. App re-renders.</p><p>3. Since App re-renders, all of its children re-render by default, including ChildComponent.</p><p>So every time you click Increment, you’ll see: Child compo is re-rendered in the console, even though buttonName never changes.</p><p>Why does this happen? React’s default behavior is: When a parent component re-renders, all of its child components re-render too.</p><p>We can solve this issue using the React.memo. Wrap the child component with React.memo.</p><p>ChildComponent.jsx:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*Q86HvuNHQUkeIGxuGxwV1w.png" /></figure><p>App.jsx: same as above.</p><p>Output: even if the Increment button was clicked multiple times, the console don’t show that the child components was re-rendered again.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*7kRA5DhYLqqJND9LYD4oAg.png" /></figure><p>But is this the ideal solution? No! React.memo actually is preventing the re-rendering until a value is passed. But if we pass a function, then it will not prevent re-rendering.</p><p>App.jsx:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*JnkqkryzLksZbgKw4t_9XA.png" /></figure><p>ChildComponent.jsx:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*ryGK0yzGjD_eGXnywrs8fg.png" /></figure><p>Output: clearly, even if we used the React.memo in ChildComponent still the re-rendering is going on.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*evZ4NzIrsE-gKBuX2FW-Cw.png" /></figure><p>Basically, Every time App re-renders, this function is recreated, since it is recreated thus for every creation there is a new reference, because the function reference changes on every render. So React.memo says: “The props changed, so I need to re-render.”</p><p>So, How to fix it? Use useCallback to memoize the function.</p><p>App.jsx:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*TGlpt43lpKCQNokmXXqdvw.png" /></figure><p>Output: Callback depending on state, and since we passed count as the dependency, thus for every click as the count is changing, the re-rendering happening, and thus here also function is recreated. ChildComponent will re-render on every count change because handleClick gets a new reference every time count changes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*KcRtWWBJnJIFkBO7SVmM-g.png" /></figure><p>Let’s see another example to understand concept of useCallback:</p><p>App.jsx:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*I92xQpAku--XkImrrVl32g.png" /></figure><p>This component demonstrates the use of useCallback. The add state is updated when the Addition button is clicked, causing App to re-render. The Learning function is wrapped inside useCallback([]), so its reference remains the same across re-renders. Since Learning is passed to ChildA, which is wrapped with React.memo, ChildA does not re-render unnecessarily when add changes. This improves performance by preventing extra renders of child components whose props haven’t actually changed.</p><p>ChildA.jsx:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*1Vet6qiIWpxegnsBRmvnCA.png" /></figure><p>ChildA is a memoized component that receives a Learning function as a prop and calls it when the button is clicked. The console.log helps us check when the component re-renders. Since the component is wrapped with React.memo, it will only re-render if the Learning prop changes. If Learning is memoized using useCallback in the parent, ChildA avoids unnecessary re-renders and improves performance.</p><p>Output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*h_oznaOUGvB_FAvySpLg_g.png" /></figure><p>“call learning function” is called:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*v2FQN7vhq8XMt923l52y2g.png" /></figure><p>“Addition” button was clicked:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*QOVGT_ZqIppaF_TgJYzWGA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/792/1*bXzOpz4w8JGxvlZnaICtJg.png" /></figure><p><strong>Updating Objects in State:</strong></p><p><strong>How to approach this?</strong></p><p>In React, state should be treated as immutable. That means when you want to update an object in state, you create a new object rather than modifying the existing one.</p><p>Let’s first understand a basic thing (without object). We are trying to update the name, as given below:</p><p>App.jsx:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*9AU2sPNF19jObvBazmRO6g.png" /></figure><p>Output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/854/1*Re1yllGSIS-jAeXsWXnFTw.png" /></figure><p>Output: when button was clicked. Name changed as expected.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*Hf6_skFUoVj05xbnhJFZrw.png" /></figure><p>This, can also be done by creating a separate function there. Right? Yes, very simple thing.</p><p>App.jsx:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/788/1*G5lDN81P2g7M6IL0XRaxnQ.png" /></figure><p>Output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/854/1*Re1yllGSIS-jAeXsWXnFTw.png" /></figure><p>Output: when button was clicked. Name changed as expected.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*Hf6_skFUoVj05xbnhJFZrw.png" /></figure><p>Also, we know if there is an object or nested object in the useState then we can access it using “.”, as shown below:</p><p>App.jsx:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*QUdJ9VMKCoRa4zlThAn_GQ.png" /></figure><p>Output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*C0BiuWWys56gFPj2IKPu8A.png" /></figure><p>Now, suppose there is an input field where user can enter the name, and we wish that name shall be displayed on the console. For that we will do like this: (we have covered this before as well)</p><p>App.jsx:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*4dS5NXdqIanGgG0snrQuww.png" /></figure><p>Output: the moment we started typing, it consoled that.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*dRxDvGZsHTWyILTnKx7SPw.png" /></figure><p>Now, suppose we want that the object shall also get changed, and reflected. For that we will use “…”.</p><p>App.jsx:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/882/1*LD09suI_4rVcBvrF7ityrw.png" /></figure><p>Output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/723/1*j7i8cxaQ6aZhoEokndLBaA.png" /></figure><p>This component stores a user’s name and address in state using useState. When the user types in the input field, handleName updates the name property and calls setData with a copied object, causing React to re-render and display the updated name. However, it directly modifies the existing state object before copying it, which is not the recommended React pattern.</p><p>Now, suppose we want to change the nested part of the object, then? See below example:</p><p>App.jsx:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*JfevH9QM8NzoCxU-PVGmHw.png" /></figure><p>This component stores a user’s name and address in state. When the user types a new city name in the input field, the handleCity function updates the city property inside the nested address object. The setData({…data, address: {…data.address, city}}) statement creates new copies of both the data object and the nested address object while updating the city value. This is done so React receives a new state object and re-renders the component to display the updated city. However, the line data.address.city = city directly mutates the state and should be avoided; the spread operator update alone is sufficient.</p><p>Output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*3g-cmn1E4n8LyoMJQzyctw.png" /></figure><p><strong>Updating Arrays in State:</strong></p><p><strong>How to approach this?</strong></p><p>In React, arrays in state should be treated as immutable, meaning you should create a new array instead of modifying the existing one. When updating an array, React needs a new array reference to detect the change and re-render the component.</p><p>First understand, displaying the array in ReactJS using State.</p><p>App.jsx:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/857/1*oBLdhthbXItv7Y3VkrGsqw.png" /></figure><p>Output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*r1chEFdwf0miopUSrrlkcg.png" /></figure><p>This component uses the useState hook to store an array of names (‘adi’, ‘uts’, and ‘pihu’) in the data state variable. Inside the JSX, the map() method is used to loop through each item in the array and render it as an &lt;h3&gt; element. The key={index} prop gives each rendered element a unique identifier, helping React efficiently update the UI when the list changes. As a result, all the names in the array are displayed on the screen as separate headings.</p><p>Now, I want that when I type a new name in the input field, the last name of the array shall get updated.</p><p>App.jsx:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*wyMqyYBsRi03bf_bygM5JA.png" /></figure><p>Output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*nlDSUrumSeqgfMGGkkHHJg.png" /></figure><p>This component stores an array of names in state and displays them using map(). When the user types in the input field, the handleUser function updates the last element of the array with the entered value. After modifying the array, setData([…data]) creates a new array copy and updates the state, causing React to re-render and display the updated last user’s name.</p><p><strong>useActionState Hook:</strong></p><p>useActionState is a React Hook (introduced with modern React and commonly used with React Server Actions frameworks like Next.js) that helps manage the state resulting from a form action.</p><p>Syntax:</p><p><em>const [state, formAction, isPending] = useActionState(</em></p><p><em>action,</em></p><p><em>initialState</em></p><p><em>);</em></p><p><strong>When should you use it?</strong></p><p>1. Form submissions</p><p>2. Server actions</p><p>3. Validation Results</p><p><strong>useActionState vs useState:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/791/1*KBMxJ-dJgUhz4wrKHUtYUw.png" /></figure><p>Let’s first create a basic form template:</p><p>App.jsx:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*PPPiO5XljXSJtTl3PWZFOA.png" /></figure><p>Output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*bbNdFsQJ0GlZbfDM0vp-tQ.png" /></figure><p>Now, introducing useActionState, to take the input, and show it on console.</p><p>App.jsx:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jwEc4Z8a00q2F9J5yYyCNA.png" /></figure><p>This React component uses useActionState to handle form submissions. When the user submits the form, the action function triggers handleSubmit, which receives the form data, extracts the name and password values, and logs them to the console. useActionState also provides data (state) and pending (loading status), though they aren’t used here.</p><p>Output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*WiURFduEh705EwHBBoJDkA.png" /></figure><p>Now, suppose in the same form, we want that there shall be a waiting period before submitting the form once the user clicked the “submit” button.</p><p>App.jsx:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/872/1*UeOu2K-Bc1uIuHBjZIWYZw.png" /></figure><p>Output: when loads.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*U-nvwALYUgBjzrz4de66Lg.png" /></figure><p>Output: when submitted we can see we have to wait for 2 seconds, before it get reflected in the console.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*Y7tNsBrknhU7w7y8QJolRw.png" /></figure><p>Now, suppose we want that when the user clicks the submit button, the submit button shall be disabled till the from is not submitted (here for 2 seconds in above case).</p><p>App.jsx: rest code be same as above for App.jsx.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*p5Z0KM4J3toYqn0mznPotA.png" /></figure><p>Output: the moment we submitted the button got disabled.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*ORahogqWrzD6ojhF9Poybw.png" /></figure><p>Output: the moment the form got submitted and shown on the console, it get enabled as well.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*ZPoE0WW42M8n-wK396fEWQ.png" /></figure><p><strong>useId Hook:</strong></p><p>useId is a React Hook that generates a unique and stable ID for a component. It is mainly used for accessibility by connecting form elements like labels and inputs.</p><p><strong>Basic Syntax:</strong></p><p><em>const id = useId();</em></p><p><strong>Why do we need useId?</strong></p><p>Consider a form with multiple inputs:</p><p><em>&lt;label htmlFor=”name”&gt;Name&lt;/label&gt;<br> &lt;input id=”name” /&gt;</em></p><p>This works fine for one input. But if the same component is rendered multiple times:</p><p><em>&lt;MyInput /&gt;<br> &lt;MyInput /&gt;</em></p><p>Both inputs would have the same ID (name), which is invalid HTML. useId solves this by generating unique IDs automatically.</p><p><strong>Advantages:</strong></p><p>· Stable across re-renders.</p><p>· Works correctly with Server-Side Rendering (SSR).</p><p>· Guaranteed unique within the React tree.</p><p>Also,</p><p>One of the biggest reasons React introduced useId is to support Server-Side Rendering.</p><p>Without useId: const id = Math.random();</p><p>Server: 0.123</p><p>Client: 0.456</p><p>React detects different HTML and may show hydration warnings.</p><p>With useId: const id = useId();</p><p>React generates matching IDs on both server and client</p><p>Example: a basic example showing that the ids generated are unique.</p><p>App.jsx:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*47Fu39FGBXLf_jECi9HUUw.png" /></figure><p>Output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*fFlrT5942XvrGAT9DNhjmg.png" /></figure><p><strong>Contact Me</strong><br>📧 <strong>Email:</strong> adii.utsav@gmail.com<br>🔗 <strong>LinkedIn:</strong> <a href="https://www.linkedin.com/in/aditya-kumar-3241b6286/">https://www.linkedin.com/in/aditya-kumar-3241b6286/</a><br>💻 <strong>GitHub:</strong> <a href="https://github.com/Rememberful">https://github.com/Rememberful</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=df7daaf8aa57" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ReactJS — Part 4]]></title>
            <link>https://medium.com/@adii.utsav/reactjs-part4-e4bca837ac45?source=rss-f1d05be749b2------2</link>
            <guid isPermaLink="false">https://medium.com/p/e4bca837ac45</guid>
            <category><![CDATA[mern-stack]]></category>
            <category><![CDATA[reactjs]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[hooks]]></category>
            <category><![CDATA[front-end-development]]></category>
            <dc:creator><![CDATA[Aditya Kumar]]></dc:creator>
            <pubDate>Tue, 21 Jul 2026 09:23:30 GMT</pubDate>
            <atom:updated>2026-07-21T09:29:47.073Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/875/0*6WhmZCwoo5rDkFxR.jpeg" /></figure><p><strong>Routing in ReactJS:</strong></p><p>Routing is the mechanism that allows a web application to change what the user sees on the screen based on the URL in the browser’s address bar.</p><p><strong>What is a Route?</strong></p><p>A Route is a specific URL path mapped to a specific component or view in your application.</p><p>Think of it as a set of instructions for your app:</p><p>· If the user visits /, show the Home component.</p><p>· If the user visits /dashboard, show the Dashboard component.</p><p>· If the user visits /settings, show the Settings component.</p><p><strong>Why Do We Need It?</strong></p><p>By default, React is a Single Page Application (SPA) framework. This means the browser loads exactly <em>one</em> HTML file (index.html) from the server. <strong>Without routing</strong>, if a user wanted to see their profile, you would have to manage that using state (e.g., if (showProfile) render Profile()). However, this introduces <strong>major issues:</strong></p><p>· <strong>No Unique URLs:</strong> The URL would always just be <a href="http://www.myapp.com./">www.myapp.com.</a> Users couldn’t bookmark their profile or share a specific page link with a friend.</p><p>· <strong>Broken Back/Forward Buttons:</strong> Clicking the browser’s back button would take the user completely out of your website, rather than just taking them back to the previous view.</p><p>· <strong>Poor SEO:</strong> Search engines struggle to index different sections of your app if they all live under a single, unchanging URL.</p><p>Routing solves all of this by syncing your app’s UI with the browser’s URL bar.</p><p><strong>Why You Should Prefer react-router-dom?</strong></p><p>react-router-dom is the undisputed industry standard for React routing for several key reasons:</p><p>· Declarative Routing: It allows you to define your routes using standard React components and hooks, fitting perfectly into the React ecosystem.</p><p>· Dynamic Matching &amp; Parameters: It easily handles complex URLs like /user/:id (where :id can be any user’s ID).</p><p>· Nested Layouts: It lets you keep a persistent sidebar or navbar while only swapping out the center content of your page.</p><p>· Performance Optimization: It includes built-in features for code-splitting and lazy-loading, ensuring your app stays fast as it grows.</p><p><strong>Command to install the react-router-dom:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*FXnbMAE1rL_DhEhBq2_X4A.png" /></figure><p><strong>To import:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/878/1*0x7kxNzS6kL8ClGnHeYlqA.png" /></figure><p>Now, let’s understand this with an example:</p><p>App.jsx:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*rctj4YEnopn1UIMM0L6spA.png" /></figure><p>Home.jsx, About.jsx, Dashboard.jsx: has basic code inside it.</p><p>Output:</p><p>Output: when we hit the url /about</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/790/1*yHDyzxwY6WAWCcWR51MMVA.png" /></figure><p>Output: when we hit the url /dashboard</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/788/1*tC-Y4Prt5UlRZoVCW4A0sw.png" /></figure><p>Clearly, it worked as intended. Now, let’s understand the part of that code:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/598/1*0o01Sw39HB-h0AfKDrHf7A.png" /></figure><p>This code creates a routing configuration for your React app. createBrowserRouter() takes an array of route objects, where each object says: “If the URL matches this path, show this component.” For example, if the URL is /, React renders &lt;Home /&gt;; if it’s /about, it renders &lt;About /&gt;; and if it’s /dashboard, it renders &lt;Dashboard /&gt;. The resulting router object is then given to &lt;RouterProvider&gt; so React Router knows how to navigate between pages without reloading the browser.</p><p>While, this code part:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/495/1*RC5u522pgar-KFrYVFPFFA.png" /></figure><p>&lt;RouterProvider router={router} /&gt; is the component that activates the router in your app. It takes the router object you created with createBrowserRouter() and tells React, “Use these route rules to decide which component to display based on the current URL.” Without RouterProvider, your routes exist as configuration, but React wouldn’t know how to use them for navigation.</p><p>But, don’t you think we have to manually enter the address in the url? Yes, to make sure we don’t do this, we will use the Navbar. For which we created a Navbar.jsx:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/878/1*Oq6Y4eIuURfCxkGWEBqntA.png" /></figure><p>Now, we have to make sure that Navbar shall be present in each page, so we have to change the App.jsx, making sure that for each url, Navbar shall be present.</p><p>For, that the part will look like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/879/1*0KGTM4KcSMdLjRRo-9dXCA.png" /></figure><p>Now, the whole App.jsx:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*GoN2Sk6FEPOlbfcdw0r6lw.png" /></figure><p>Output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/703/1*oK5vBLk69Jn7-M1uVs39_g.png" /></figure><p>Output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/638/1*g6BUYhz5P5bWfcellzl2zg.png" /></figure><p>Output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/734/1*7TjtrXYBWVWD4kf_YZ4-Cg.png" /></figure><p>Observe that the page is not reloading. Fulfilling the goal of SPA of the react. But what actually happening in the background?</p><p>The browser does not reload the entire page. Instead:</p><p>1. React Router changes the URL using the browser’s History API.</p><p>2. It checks which route matches the new URL.</p><p>3. It unmounts the old route component (for example, &lt;Home /&gt;).</p><p>4. It mounts the new route component (for example, &lt;About /&gt;).</p><p>5. Components that are outside the changing area (like a Navbar) remain on the screen and are not recreated.</p><p>Now, you would have observed some kind of parameters passed in the URL when we visit a link? Right? Yes!</p><p><strong>What are the parameters?</strong></p><p>In routing, parameters (often called URL params or dynamic routes) are placeholders in a URL path that allow you to capture dynamic values. Instead of creating a unique route for every single user, product, or article (e.g., /user/1, /user/2, /user/3), you define one single route with a parameter placeholder.</p><p><strong>How to Define a Route Parameter?</strong></p><p>In react-router-dom, you define a parameter by placing a colon (:) in front of the parameter name inside your path string.</p><p>Example:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/815/1*ieu8bZLtFY8PBExWlI0qvQ.png" /></figure><p>Now, the App.jsx:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*So5pRo4eevSMlk541F6Gbw.png" /></figure><p>And the new component which we created, Paramcomp.jsx:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*ja7kZLkDxJIWyar2DBBh3w.png" /></figure><p>Output: the moment we type /student/abcd in the URL.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*xHhUjY2kSdJHg-LVkt-grw.png" /></figure><p>Now, there is something called as useNavigate hook.</p><p><strong>What is useNavigate hook?</strong></p><p>The useNavigate hook is used for programmatic navigation. It allows you to redirect users to different pages using code logic (e.g., inside functions, event handlers, or useEffect blocks) rather than relying on a direct user click on a &lt;Link&gt; component.</p><p><strong>When to Use useNavigate vs. &lt;Link&gt;</strong></p><p>· Use &lt;Link&gt; (Declarative): For static navigation where the user directly initiates the change by clicking (e.g., Navbars, Menus, Footers).</p><p>· Use useNavigate (Programmatic): For dynamic navigation triggered by background code or after an event finishes executing.</p><p>Example: suppose we add a button on the home page to navigate to the dashboard.</p><p>Home.jsx:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/891/1*u4LdVOMJ108dIHfQVdg4Ug.png" /></figure><p>Output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/906/1*kEY3O_qVqjUYNv9sS10URQ.png" /></figure><p>Output: when clicked on the button.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*0szhSTRtYsermDXshjXkow.png" /></figure><p>Done!</p><p>Now, we will study about the concept of Nested routing:</p><p><strong>What is Nested Routing?</strong></p><p>Nested Routing is the practice of rendering routes <em>inside</em> other routes. It allows you to build complex user interfaces where parts of the page stay exactly the same (like a sidebar, layout header, or dashboard menu) while other parts of the page dynamically swap content based on the sub-path.</p><p>Think of an application dashboard. The top navigation bar and left sidebar should stay on the screen at all times. When a user switches between “Analytics” and “Settings,” only the center content panel changes.</p><p>· URL /dashboard -&gt; Shows Dashboard Layout + General Stats</p><p>· URL /dashboard/analytics -&gt; Shows Dashboard Layout + Live Graphs</p><p>· URL /dashboard/settings -&gt; Shows Dashboard Layout + Settings Forms</p><p><strong>How to set up Nested routing?</strong></p><p>To set up nested routing using createBrowserRouter, you pass an array of routes to the children property of a parent route.</p><p>Example:</p><p>App.jsx:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/883/1*Zr-YkfvguVQB-G_uudnsMA.png" /></figure><p>Dashboard.jsx:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/592/1*CmjVFB5j1uDTM-zH0R-7_g.png" /></figure><p>Output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*iNBQArwl-i_a-shDnphsiw.png" /></figure><p>Output: for /setttings</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*NxzETMNL-xpR9W-AX9n4Yw.png" /></figure><p>Also,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/412/1*TJJ_2naHhLmQQObFXhD3Bg.png" /></figure><p>Also,</p><p>· <strong>BrowserRouter</strong>: Enables client-side routing in a React application using the browser’s History API.</p><p>· <strong>Routes</strong>: Acts as a container for all Route components and renders the component that matches the current URL.</p><p>· <strong>Route</strong>: Defines a specific URL path and the component that should be displayed when that path is matched.</p><p>· <strong>Link</strong>: Used to navigate from one page to another without reloading the entire page.</p><p>Also,</p><p><strong>Client-Side Routing</strong></p><p>· Routing is handled by the browser using JavaScript.</p><p>· The page does not reload when navigating between routes.</p><p>· Only the required component or content is updated.</p><p>· Provides a faster and smoother user experience.</p><p>· Commonly used in React applications with libraries like React Router.</p><p><strong>Server-Side Routing</strong></p><p>· Routing is handled by the web server.</p><p>· Each time a user navigates to a new URL, the browser sends a request to the server.</p><p>· The server processes the request and returns a new HTML page.</p><p>· The entire page reloads on every navigation.</p><p><strong>useRef Hook:</strong></p><p><strong>What is useRef?</strong></p><p>The useRef Hook in React is used to store a value that persists between renders without causing a re-render when it changes.</p><p><strong>When to use useRef?</strong></p><p>It’s commonly used for:</p><p>1. Accessing DOM elements directly.</p><p>2. Storing mutable values (timers, previous values, etc.).</p><p>3. Preserving values between renders without triggering updates.</p><p>Syntax:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/521/1*uiTDjSi-cMtaOALgJQBwyQ.png" /></figure><p>Example: without useRef.</p><p>App.jsx:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*mOZNrnXhEJDqu7PFaz3r7w.png" /></figure><p>Output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/915/1*DWoxp_bYVehid9wVlU6u-g.png" /></figure><p>Example: now making the input field get focused when someone click on the button, using the useRef.</p><p>App.jsx:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*8M-VGZpmnvjM8X7qMxVmyQ.png" /></figure><p>In this code, useRef(null) creates a reference called inputRef that is attached to the &lt;input&gt; element using ref={inputRef}. When the button is clicked, the inputHandler function runs and uses inputRef.current to directly access the actual input box in the DOM. It then focuses the input field (focus()), changes the text color to red (style.color = ‘red’), and updates the placeholder text to “Enter password”. In simple terms, useRef lets you directly work with a DOM element without re-rendering the component.</p><p>Output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*yHjXoZWand9ydS6qLEDRYQ.png" /></figure><p>Output: when you clicked on the button, and started writing. We see that placeholder is changed, focus came on the input field, and the text colour also got changed to red.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*mSHeA_jeRs6J2qciGxajng.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/808/1*Ox8_vR0Ncb0hSgcycC2dGQ.png" /></figure><p>Also, we can use the useRef hook to hide and show, although it is not a good practice to do so.</p><p>App.jsx:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*7StFBkAP-PHih5iBa9Ay8A.png" /></figure><p>In this code, useRef(null) creates a reference to the &lt;input&gt; element and stores it in inputRef. When the Toggle input field button is clicked, the toggleHandler function checks the input’s current display style. If the input is visible (display is not ‘none’), it hides the input by setting display = ‘none’. If the input is already hidden, it makes it visible again by setting display = ‘inline’. In simple words, useRef is being used to directly access the input element and show or hide it without using React state.</p><p>Output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*337tO3c_xz8jewBxXoqR2g.png" /></figure><p>Output: when clicked on the button, input field hided.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/748/1*F1bDqa7EI_X4t8Fgs_CpKg.png" /></figure><p><strong>Use case 1:</strong> when a variable persists its value across every re-render.</p><p>Example: where the variable can’t manage to persists its value across re-render. No useRef hook is used here.</p><p>App.jsx:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*CrIZ_AElHjl0Sfzj6sw1uA.png" /></figure><p>Output: when loaded.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*mKQ477M7vB8v3S8dYEcBVg.png" /></figure><p>Output: when clicked on the button for few times, we expected that console shall show that value of val is also increased, but it didn’t. It mean val can’t manage to persist its value on re-render.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*bBifBugVfSzuO86fdjJbow.png" /></figure><p>In this code, useState is used to manage count, so when the button is clicked, the UI updates correctly. But val is a normal variable, so every time the component re-renders, it resets back to 1, meaning its updated value is not preserved in React. Only count changes the UI because it is stored in state, while val only changes temporarily inside the function and is lost after re-render.</p><p>So, what’s the solution? Use useRef.</p><p>App.jsx:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/920/1*vKo-yiik5524DQeBG_uFHg.png" /></figure><p>Output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*p4p3xuvMdlE0ejd66_52cw.png" /></figure><p>Output: when clicked for few times.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*PtABcId2LdOy0GGqoy8Wnw.png" /></figure><p>In this code, useState is used to manage count, so the UI updates every time the button is clicked. The variable val is created using useRef(0), which stores a value that persists across re-renders without resetting. When the button is clicked, val.current increases and keeps its updated value, and it is logged in the console, while setCount triggers a re-render to update the UI. In simple words, useRef is used here to remember a value between renders without affecting the UI.</p><p><strong>Normal Variables vs Variables created using useRef:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/793/1*KfhPAjPLbyF68rNCtjbBvQ.png" /></figure><p><strong>Use case 2:</strong> When we want to access a DOM element directly.</p><p>App.jsx:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*C1flQ6zfJs0955j_K2LHUw.png" /></figure><p>Output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/620/1*w5LmQR9JsngLsEo8PFJLCg.png" /></figure><p>Output: when 2nd button was clicked.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/821/1*c6H_CwTeQ3_tilt4mOpXVw.png" /></figure><p>In this code, useState is used to manage the count value so the UI updates when the button is clicked, while useRef is used for two different purposes: val stores a value that persists across renders without affecting the UI, and btnRef is used to directly access the first button element in the DOM. When the first button is clicked, handleIncrement updates both the ref value and the state, and when the second button is clicked, changeColor directly changes the background color of the first button to red using btnRef.current, showing how useRef can be used for direct DOM manipulation.</p><p><strong>uncontrolled component:</strong></p><p><strong>What is uncontrolled component?</strong></p><p>In React, an uncontrolled component is a form element (like an input, textarea, or select) where the DOM itself manages the state, rather than React. Instead of storing the input value in React state and updating it on every change, you let the browser handle it, and you read the value only when needed (usually using a ref).</p><p><strong>Key characteristics</strong></p><p>· The DOM stores the form data</p><p>· React does not control the value in real time</p><p>· You typically use ref to access the value</p><p>· Less code for simple forms</p><p><strong>Controlled vs Uncontrolled component:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/782/1*jus4k8yrqFKCdCyeD9_-KA.png" /></figure><p><strong>When to use uncontrolled components?</strong></p><p>Use them when:</p><p>· You don’t need instant validation or live updates</p><p>· You want simpler code</p><p>· You’re integrating with non-React libraries</p><p>· You only need values on submit</p><p>Example: a form controlled by DOM (basically uncontrolled component)</p><p>App.jsx:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/876/1*1eJEEFXj9Nc9bZxi6MS76A.png" /></figure><p>Output: ignore those errors, they are because of the extension I have.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*9IF6eGVyzFYmIboLKqpBoA.png" /></figure><p>Output: fill it and then submit. We can see the entered value in the console.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*_ULtJYnAqGmxWqPKM89f8A.png" /></figure><p>This component renders a username and password form. When the form is submitted, handleForm prevents the page refresh, gets the input values directly from the DOM using document.querySelector(), and prints them in the console. Since React does not store the input values in state, it is an uncontrolled component.</p><p>Now, handling the same thing using the <strong>useRef.</strong></p><p>App.jsx:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/776/1*eyYat6GDkwqzLeBHq1o78g.png" /></figure><p>Output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*uz4ODzTuaoMBgRiQWxqR8w.png" /></figure><p>Output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*wqbOFiCtOQD9PqVn5wbkRw.png" /></figure><p>Now, some more examples of the useRef:</p><p>App.jsx:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*mPBb56Ak__UyhTEVZeg9cQ.png" /></figure><p>ColorChanger.jsx:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*C9bmCTwLwEhtUXnNo-DYHg.png" /></figure><p>Output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*dRUaIq9mcJwjNLE8EIWGLw.png" /></figure><p>Output: when I wrote the colour name and clicked on the “Change BGC” button.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*nId30ZjQF-7lHNcsdoyFog.png" /></figure><p><strong>Pass Function in Component as Props:</strong></p><p>Passing a function as a prop in React means sending a function from a parent component to a child component, so the child can execute some logic that belongs to the parent. This is one of the most important concepts in React because it allows child components to communicate with parent components.</p><p>Example: normally what we do?</p><p>App.jsx:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*z2qB10HqAmqdCbEdNTFYzw.png" /></figure><p>User.jsx:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*uT3xfPVqZEAuYTNfy6S51Q.png" /></figure><p>Output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*j865jIalwWBOlfSUjR50iQ.png" /></figure><p>Output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*iTiH8oop9jGyE8LteiaLog.png" /></figure><p>Observe, when we do one &lt;User/&gt; in the App.jsx, the whole code is rendered once, while if we do multiple &lt;User/&gt;, it will get rendered multiple times. This is long run is not a good idea. Instead we will use the function inside the App.jsx, as given below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*EUjJ4W9lAXGsukKHZCpU2g.png" /></figure><p>User.jsx:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*qVqlFW5NgUVNcsASFNW38g.png" /></figure><p>Output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*cYbcFPCY5gCGt_5e8FQvxQ.png" /></figure><p><strong>Passing PROPS as Children and Functions:</strong></p><p><strong>What is Children?</strong></p><p>The children prop is a special prop in React that contains everything you put between a component’s opening and closing tags.</p><p>Example:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/848/1*ziSCPc2mStuImnxiCWi56A.png" /></figure><p>Now, we can see this usage using a basic example.</p><p>App.jsx:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*DES8HDaiHKPaRbC9k9si3g.png" /></figure><p>Card.jsx:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/917/1*InaofuICuJ8KpKwmK5jhqw.png" /></figure><p>Output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/890/1*LqbBaWvpMZ9gOdffgjzLVw.png" /></figure><p>props.children is a special React prop that represents the content placed inside a component, and {props.children} renders that content at that location in the component’s JSX.</p><p>Since, there is another way to create the children, using the “children=”.</p><p>App.jsx:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*d4R-VL4jStqoF649SE3nkg.png" /></figure><p>Card.jsx:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*q0_EVqsrtet6NiQer0l1Ng.png" /></figure><p>Output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*Ogt-fOC_6cej8Zfuzi-vAw.png" /></figure><p>Now, we will learn how to pass a function from parent to child.</p><p>App.jsx:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*i4Vo9Ru5WSYzULv7iqxzFA.png" /></figure><p>This code creates a React app that keeps track of a number using useState. The count variable starts at 0, and the handleClick function increases the count by 1 whenever it is called. The current count is displayed inside an &lt;h1&gt; tag. The Button component is then used and receives two props: incrementCount, which is the function that updates the count, and text, which sets the button’s label to <strong>“Click me”</strong>. When the button is clicked, the number on the screen increases by one.</p><p>Button.jsx:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*1jGhddSG07vM_NPlztZ3Wg.png" /></figure><p>It receives information through props, such as the button text (props.text), a function to run when the button is clicked (props.incrementCount), and any content placed inside the component (props.children). The component displays the child content first and then shows a button. When the user clicks the button, the incrementCount function is executed, and the button displays the text passed through props.text. Finally, the component is exported so it can be used in other files.</p><p>Output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*IwVAmA-rwa01r0kDGBFrNQ.png" /></figure><p><strong>forwardRef:</strong></p><p><strong>What is forwardRef?</strong></p><p>In React, forwardRef is a method that allows a parent component to pass a ref to one of its child component’s DOM elements. forwardRef is a React API that allows a parent component to pass its ref through a custom child component and access the child’s underlying DOM element or component instance.</p><p>forwardRef is a React utility that allows a parent component to pass a ref through a custom component to one of its child DOM elements.</p><p>Without forwardRef, refs work only on:</p><p>· HTML elements (input, div, button, etc.)</p><p>· Class components</p><p>They don’t automatically work on function components.</p><p>Example: old way (for versions below React 19). Here, we are coding such that when we click on the button the input field should get the value 100 and it shall also get focused.</p><p>App.jsx:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/882/1*ZXUCu_RftNQiDmo8aN_Crg.png" /></figure><p>UserInput.jsx:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/931/1*JWRhC-79hVzFZ99VaBz41A.png" /></figure><p>Output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/715/1*kEaqy-KDHIKXJbkdn2cF1g.png" /></figure><p>Output: when button was clicked.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/672/1*iiK_pOEPExq7aeISr9fxtQ.png" /></figure><p>Example: new way (for versions above and equal to React 19). Same thing we will try to do.</p><p>App.jsx: same as above.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*hBW81vWyJdmtDNut10-Uew.png" /></figure><p>UserInput.jsx:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*7CbvbtN0iI_6dSJISocwvw.png" /></figure><p>Output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/715/1*kEaqy-KDHIKXJbkdn2cF1g.png" /></figure><p>Output: when button was clicked.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/672/1*iiK_pOEPExq7aeISr9fxtQ.png" /></figure><p><strong>Contact Me</strong><br>📧 <strong>Email:</strong> adii.utsav@gmail.com<br>🔗 <strong>LinkedIn:</strong> <a href="https://www.linkedin.com/in/aditya-kumar-3241b6286/">https://www.linkedin.com/in/aditya-kumar-3241b6286/</a><br>💻 <strong>GitHub:</strong> <a href="https://github.com/Rememberful">https://github.com/Rememberful</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e4bca837ac45" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ReactJS — Part 3]]></title>
            <link>https://medium.com/@adii.utsav/reactjs-part-3-5f214450f9fa?source=rss-f1d05be749b2------2</link>
            <guid isPermaLink="false">https://medium.com/p/5f214450f9fa</guid>
            <category><![CDATA[reactjs]]></category>
            <category><![CDATA[mern-stack]]></category>
            <category><![CDATA[front-end-development]]></category>
            <category><![CDATA[hooks]]></category>
            <category><![CDATA[web-development]]></category>
            <dc:creator><![CDATA[Aditya Kumar]]></dc:creator>
            <pubDate>Mon, 20 Jul 2026 01:01:02 GMT</pubDate>
            <atom:updated>2026-07-20T01:01:02.108Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/875/0*6gXr4KAxSpukYrHt.jpeg" /></figure><p><strong>useEffect in ReactJS:</strong></p><p><strong>What is useEffect?</strong></p><p>· useEffect is a React Hook used to run some code after the component renders.</p><p>· useEffect is a React Hook used to handle “side effects”.</p><p>· useEffect is a React Hook that lets you synchronize a component with an external system.</p><p><strong>What does Side effects mean?</strong></p><p>Things that happen outside the normal rendering process, like:</p><p>· Fetching data from an API</p><p>· Timers (setTimeout, setInterval)</p><p>· Updating the browser (like document.title)</p><p>· Connecting to external systems (WebSocket, subscriptions)</p><p><strong>Why do we need useEffect?</strong></p><p>Sometimes we want to do extra work <em>after</em> the UI renders. That’s where useEffect comes in.</p><p><strong>Basic Syntax:</strong></p><p><em>useEffect(() =&gt; {</em></p><p><em>// side effect code here</em></p><p><em>}, [dependencies]);</em></p><p>It has 2 parts:</p><p>1. Function → what to do</p><p>2. Dependency array (optional) → when to do it</p><p>While the snippet of useEffect has three value:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/719/1*axeFtOOiyxK562G10_wIwQ.png" /></figure><p><strong>first — Side Effect logic</strong></p><p>This code runs:</p><p>· After the component renders for the first time.</p><p>· Again whenever any dependency in the array changes.</p><p><strong>second — Cleanup function</strong></p><p>The function returned from useEffect is the cleanup function.</p><p>It runs:</p><p>· Before the effect runs again due to dependency changes.</p><p>· When the component unmounts.</p><p><strong>third — Dependency</strong></p><p>Values listed in the dependency array tell React when to re-run the effect.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/782/1*fCy7sjrWoJQa6BRzCQ7kOQ.png" /></figure><p>Now, let’s understand with examples:</p><p><strong>Variation 1: </strong>runs on every render.</p><p>Example:</p><p>App.js:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*CuHXB6WTo5MpYBVBHnN2hQ.png" /></figure><p>Output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*EVn8_kywMtGLTq6fSNNXBA.png" /></figure><p>Since, it is in restrict mode, so it will appear again, and when clicked on “OK”, the text of &lt;h1&gt; will come.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*QL96RqG0eUztxDvM1FPt2Q.png" /></figure><p>This code creates a React component called App. Inside it, useEffect() is used without a dependency array, which means the code inside it runs after every render of the component. In this case, it shows an alert saying “I will run on every render…” each time the component renders. The component also displays the heading “Aditya” on the page. Since the effect runs on every render, the alert will keep appearing whenever the component re-renders.</p><p>Another example of “runs on every render”.</p><p>App.js:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*W7yXzNqsxZJYNHeX0hEzJw.png" /></figure><p>Output: this comes on first render. When the screen loaded for the first time.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*EVn8_kywMtGLTq6fSNNXBA.png" /></figure><p>When clicked OK:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/602/1*JCiSITMEvmjS1rcazPUrtw.png" /></figure><p>When clicked on the “Click Me!” button: again it aimed to re-render the count from 0 to 1, but since useEffect is used, it will run before the count to increase from 0 to 1.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*kVTnO10rLCl4lPFdmzhRAQ.png" /></figure><p>Once, we click “OK” again: count get increased from 0 to 1.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*3OA7LNsln8tjgWO5IlPOpA.png" /></figure><p>This component displays a name, a button, and a counter. The count state starts at 0. When you click the “Click Me!” button, the handleClick function increases the count by 1 using setCount(). Since updating state causes the component to re-render, the useEffect() hook runs again. Because no dependency array is provided, the effect runs after every render, so the alert “I will run on every render…” appears when the component first loads and again every time the button is clicked and the count changes.</p><p>Now, other variations..</p><p><strong>Variation 2: </strong>that runs on only the first render.</p><p>Basically, the main logic snippet be this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/870/1*ein0b7aaLkq4GfxezSQajA.png" /></figure><p>When the page loads, the alert appears once. Clicking a button or updating state later will re-render the component, but the useEffect will not run again because there are no dependencies to watch for changes.</p><p>Let’s see this using an example:</p><p>App.js:</p><p>Output: when it loaded for first time.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*jNhlUt0GRm1D6QJMC7MZ1A.png" /></figure><p>When clicked OK, and clicked on the “Click Me!” button: no alert comes again, simply the count increases from 0 to 1, and so on.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*CgB_cEZlP0OmZ2OV4QI7EA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*n6c_1wdAWe9aKU9wlXpERA.png" /></figure><p>This component uses useState to keep track of a counter that starts at 0. The useEffect hook has an empty dependency array ([]), so it runs only once, right after the component is rendered for the first time. As a result, the alert “I will run on only the first render…” appears only when the page initially loads. When the “Click Me!” button is clicked, the count state increases and the component re-renders to show the updated count, but the useEffect does not run again because its dependency array is empty.</p><p><strong>Variation 3: </strong>there is something inside the dependencies.</p><p>Main logic snippet:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/914/1*nBAXrQGqqKL2D8HZyB-A1w.png" /></figure><p>React watches count, and whenever count changes, it executes the code inside useEffect.</p><p>Example:</p><p>App.jsx:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*ab_Wnk3tLsEbc3bLYqzJUA.png" /></figure><p>Output: when screen loaded, the count was assigned ‘0’ and thus the logic of useEffect was executed as well.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*REIRK9e0ILKHf3W2PKQwMw.png" /></figure><p>When clicked on “OK” and then clicked on the “Click Me!” button: the alert box will come again.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*K91yBl4SjpyFETcMuYTHGA.png" /></figure><p>When clicked “OK”: count will get updated from 0 to 1. And for every update in the ‘count’ there will be Alert box coming.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*PUEK088PNtZYAVbaSy2pnA.png" /></figure><p>This component displays a counter that starts at 0. The useEffect hook has count in its dependency array ([count]), so React runs the effect after the component first renders and then every time the count value changes. When you click the “Click Me!” button, the handleClick function increases the count by 1 using setCount(count + 1). This updates the state, causes a re-render, and since count changed, the useEffect runs again and shows the alert “I will run everytime when count is updated”. As a result, you’ll see the alert when the page first loads and after each button click.</p><p><strong>Variation 4: </strong>multiple dependencies.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*xDHU0E3o4uZKs-AxukmQcg.png" /></figure><p>React watches both count and total. Whenever either one is updated, the code inside useEffect executes.</p><p>Example:</p><p>App.jsx:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*fO1lkOYhUrrAUlJjQ1dP7Q.png" /></figure><p>Output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*Z4bG408xCW9WJphXoUmjQQ.png" /></figure><p>When clicked on “OK” and then clicked on either of the buttons: again the alert will come.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*IiYaDNIMji97OrZ_wiR8cg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*hiIf5GBaAWSi4EqzT5AdvA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*0sjeev0450_uByTjNiA7cA.png" /></figure><p>This component uses two state variables: count, which starts at 0, and total, which starts at 1. The useEffect hook has [count, total] as its dependency array, so it runs once when the component first renders and then every time either count or total changes. Clicking “Click Me for Count!” increases the count value, while clicking “Click Me for Total!” increases the total value. Whenever either button is clicked, the component re-renders and the alert “I will run everytime when count/total is updated” appears because one of the dependencies has been updated. The current values of count and total are displayed on the screen and update automatically after each click.</p><p><strong>Variation 5: </strong>With cleanup function</p><p>Main code snippet:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/769/1*kpVGrtEpEmKP7uY2RH9Zog.png" /></figure><p>This useEffect runs when the component first loads and whenever count changes. When count is updated, it first runs the cleanup function from the previous effect, showing the alert “count is unmounted from UI”, and then runs the new effect showing “Count is updated”. The cleanup is not actually about unmounting the whole component here — it runs before the effect runs again due to dependency changes. So in simple terms: whenever count changes, React first clears the previous effect, then runs the new one.</p><p>Example:</p><p>App.jsx:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*hyQ9u0-bQqoCefvLiI_egw.png" /></figure><p>Output: when the screen loaded.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*6abcq7J8vuq-UmWQ6zPAsQ.png" /></figure><p>When clicked on “OK”, the 2nd alert box came:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*LwvzBXzZi3vlGCviNEePwQ.png" /></figure><p>When clicked on “OK” again:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*UiGq9ysbpvfuiF8Hc4tVgg.png" /></figure><p>When clicked on to update the count: the “count is unmounted from UI” is displayed first, this is because the previous value of count is unmounted now before updating.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*L_8lKl2Gvx6G5xAdOpJ07g.png" /></figure><p>Then the count is updated alert box will come:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*Lgo1sDHQ_28IHKPMKdPH6Q.png" /></figure><p>Then the count is updated from 0 to 1:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*GrOlIBsqVKQ0gtpfZNSI4g.png" /></figure><p>Also, when clicked to increase the “Total”: no alert box will come.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*l5KgSnAi7T3dIu5dmTz75g.png" /></figure><p><strong>Use Effect Hook for Life Cycle Methods in React:</strong></p><p><strong>What are the phases of life cycle in react?</strong></p><p>In React, a component lifecycle means the different stages a component goes through from the time it is created until it is removed from the screen.</p><p>Think of it like a person’s life:</p><p>1. Birth → Component is created.</p><p>2. Growth → Component updates when data changes.</p><p>3. Death → Component is removed.</p><p><strong>Phases of React Component Lifecycle:</strong></p><p><strong>1. Mounting Phase (Component is Created): </strong>This phase happens when the component is added to the screen for the first time.</p><p><strong>2. Updating Phase (Component Changes): </strong>This phase happens when:</p><p>· State changes (setState)</p><p>· Props change</p><p>· Force update occurs</p><p><strong>3. Unmounting Phase (Component is Removed): </strong>This phase happens when the component is removed from the screen.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/721/1*ZaJsrh3t8Fd8zeNqVAW62Q.png" /></figure><p><strong>useContext in ReactJS:</strong></p><p>Let’s first understand the concept of Prop Drilling: (even before it, revisiting Props)</p><p><strong>What is Prop?</strong></p><p>Props (short for <em>properties</em>) are used to pass data from a parent component to a child component.</p><p>Example:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*ze0W-gIhrr5PVQZgPl7Qdg.png" /></figure><p>Here:</p><p>· App is the parent.</p><p>· Child is the child.</p><p>· name=”Aditya” is passed as a prop.</p><p>Output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*WL-r2ZrE5DTgeF1GSzFwgQ.png" /></figure><p><strong>What Problem Does Prop Drilling Solve?</strong></p><p>Imagine you have this component structure:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*Pa4nEZTcuNmbd5Pay4DwIA.png" /></figure><p>Suppose a value is stored in App, but GrandChild needs it. Since React data normally flows parent → child, the value must travel through every intermediate component. This process is called Prop Drilling.</p><p><strong>So, what is prop drilling?</strong></p><p>Prop Drilling is the process of passing data from a parent component to a deeply nested child component through multiple levels of components using props. Even if intermediate components don’t need the data, they still have to pass it down.</p><p><strong>Why prop drilling can become a problem?</strong></p><p>1. Lots of Repeated code</p><p>2. Harder to maintain</p><p>3. Intermediate Components Become Unnecessary Messengers</p><p><strong>Is Prop Drilling a React Hook?</strong></p><p>No. Prop Drilling is not a hook. It is simply a pattern of passing props through multiple levels.</p><p><strong>Difference Between Prop Drilling and Hooks:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/672/1*NCGmZjiiEzAgpFjZVCBFoA.png" /></figure><p>Example: a basic example of prop drilling.</p><p>App.jsx:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*F5zTRgkQ0Ya04p0YWO-Mzw.png" /></figure><p>Parent.jsx:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*iUqdJplkk0W-IZCYfvK2hQ.png" /></figure><p>Child.jsx:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*Y86Kk3GwM6Ee8eoUV-HRuw.png" /></figure><p>GrandChild.jsx:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*1G9V-UgupglgafcqMM89LQ.png" /></figure><p>Output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*EoJt166onOZK-A7eca3n1w.png" /></figure><p>Step-by-step</p><ol><li>App creates:</li></ol><p><em>const theme = “Dark Mode”;</em></p><p>2. App passes it to Parent:</p><p><em>&lt;Parent theme={theme} /&gt;</em></p><p>3. Parent receives it:</p><p><em>function Parent({ theme })</em></p><p>and passes it to Child:</p><p><em>&lt;Child theme={theme} /&gt;</em></p><p>4. Child receives it:</p><p><em>function Child({ theme })</em></p><p>and passes it to GrandChild:</p><p><em>&lt;GrandChild theme={theme} /&gt;</em></p><p>5. GrandChild finally uses it:</p><p><em>&lt;p&gt;Theme: {theme}&lt;/p&gt;</em></p><p>So, basically prop drilling is an issue, which can be overcome using the useContext hook or also called useContext API.</p><p><strong>What is useContext?</strong></p><p>useContext is a React Hook that lets a component access data from a Context without passing that data through props at every level.</p><p>useContext has three basic steps:</p><p>1. Create Context</p><p>2. Provide</p><p>3. Consume</p><p>So, for earlier problem:</p><p>Instead of passing props through every component, GrandChild can directly ask React: <em>“Give me the user stored in Context.” </em>No prop drilling needed.</p><p>Now, let’s understand the steps of useContext step by step:</p><p>First see the folder structure for this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/456/1*EiLjmI-kKnEJDnJsZqTxTw.png" /></figure><p>Step1: Create Context</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*EQ20C7IWNpw9N8mD9Xlmng.png" /></figure><p>This creates a “global container”.</p><p>Step2: Wrap all the child inside a provider. Basically, we are wrapping every child which we want to be consumer.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/395/1*1oGjbl5hX-2fG6y_qfWmHQ.png" /></figure><p>So, now App.jsx, looks like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/845/1*LL2seaioNFQGq7Rr_dUe2w.png" /></figure><p>Step3: Pass Value</p><p>For this first create the value:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/761/1*GmXLtEkRcL_ISmr__9-QwA.png" /></figure><p>Now, passing the value:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/688/1*LcYJomSzMz8C8G7jaGoGqg.png" /></figure><p>So, now the App.jsx: notice that we are exporting the “UserContext” as well.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/720/1*Qewq43BYBl-WRDcxTJ0roQ.png" /></figure><p>Step4: Consume value.</p><p>For this, the code of the child be given below:</p><p>ChildA.jsx:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/709/1*XCWPMoZXlycIudMvhvGFBA.png" /></figure><p>ChildB.jsx:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/713/1*7WW5X9yRg6NHHlxfczXepw.png" /></figure><p>ChildC.jsx: here we are using the value.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*RpbhED_q1LX3evNEtIhUOg.png" /></figure><p>Output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*iHclYXfR3pId8KgFDuOdCg.png" /></figure><p>Now, let’s understand the useContext with another example:</p><p>App.jsx:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*ERTULHEgrT7kl_7jAYuS8w.png" /></figure><p>ChildA.jsx:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*rZD59im9dsukJgsqFnlidw.png" /></figure><p>ChildB.jsx:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*6ozW3SHqFT9BTq266RVpag.png" /></figure><p>ChildC.jsx:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*QRjWx8sIlvw_YstATnub9Q.png" /></figure><p>Output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/728/1*-I7Yjpkw9iJe_UYxRgTzOw.png" /></figure><p>Output: if clicked.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*rwwwI6VeOXf4Defwjw-izQ.png" /></figure><p><strong>How useContext is different from other hooks?</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/413/1*tUPLjvEkOc7pR5PS3wwEZg.png" /></figure><p><strong>Styling in React JS:</strong></p><p>There are 5 common ways to style React applications:</p><p>1. Inline Style</p><p>2. External CSS</p><p>3. CSS Modules</p><p>4. Styled Components</p><p>5. External CSS Libraries/Frameworks (Bootstrap, Tailwind CSS, Material UI)</p><p><strong>Contact Me</strong><br>📧 <strong>Email:</strong> adii.utsav@gmail.com<br>🔗 <strong>LinkedIn:</strong> <a href="https://www.linkedin.com/in/aditya-kumar-3241b6286/">https://www.linkedin.com/in/aditya-kumar-3241b6286/</a><br>💻 <strong>GitHub:</strong> <a href="https://github.com/Rememberful">https://github.com/Rememberful</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5f214450f9fa" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ReactJS — Part 2]]></title>
            <link>https://medium.com/@adii.utsav/reactjs-part-2-d5a25ef7ce98?source=rss-f1d05be749b2------2</link>
            <guid isPermaLink="false">https://medium.com/p/d5a25ef7ce98</guid>
            <category><![CDATA[mern-stack]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[part-2]]></category>
            <category><![CDATA[reactjs]]></category>
            <dc:creator><![CDATA[Aditya Kumar]]></dc:creator>
            <pubDate>Sat, 18 Jul 2026 05:45:03 GMT</pubDate>
            <atom:updated>2026-07-18T05:45:03.170Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/875/0*IxkaEIfmLf8mP17q.jpeg" /></figure><p><strong>Understanding Props and PropTypes in React:</strong></p><p>Let’s first understand the difference between export default vs named export in React.</p><p><strong>What are exports?</strong></p><p>In React, we use exports to share code from one file to another. There are two main types:</p><p>1. export default</p><p>2. export (named export)</p><p><strong>What is ‘export default’?</strong></p><p>What it means: A file can have only ONE default export</p><p>It is used when:</p><p>· You want to export main thing from a file</p><p>Example: a basic example.</p><p>Create a new file named, Module1.mjs:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*nQPI7TxIYtXvhbcmHq9hpw.png" /></figure><p>And one another file named, Modul2.mjs:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/883/1*4Wc4pAdfAOOyrffN_klSeA.png" /></figure><p>Now, in terminal try to run the Module2.mjs using the node:</p><p><strong>What this output indicates about the ‘export default’?</strong></p><p>It exports one main value from a file. Even though you had 3 variables (a, b, c), only this one was exported: <em>export default a; </em>(look at line 5 of Module1.mjs). Also, we can name the import anything you want, here we wrote ‘import any_name’ but still got the ‘Aditya’. So this shows: default export is NOT bound to a name.</p><p>Only ONE default export is allowed per file, if one write like this in Module1.mjs:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/903/1*NfQFJm4g7EboFFIdjbuAiA.png" /></figure><p>And then try to run the node: it will give the error.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*AcjYkrEeNXnJ3JUhoWDLsg.png" /></figure><p>Now, let’s talk about named exports.</p><p><strong>What are ‘named export’?</strong></p><p>What it means: You can export multiple things from a file.</p><p>Example: Module1.mjs:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/739/1*zAh7j-VuJCK8U1Yb5WAq2g.png" /></figure><p>While Moduel2.mjs:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/897/1*LMUh2UtRea6-mYtfdbBZ-A.png" /></figure><p>Now, in the terminal:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*IZIkCwJm6fnW_LJy0aMYNw.png" /></figure><p><strong>What you learn from this output about ‘named export’?</strong></p><p>· Names are FIXED in named exports, we must use the exact same names.</p><p>· You can import only what you need</p><p>· Multiple exports are allowed (unlike default)</p><p>· You can rename while importing (using ‘as’)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*OosLmsBdt5QABy4qNb_Umg.png" /></figure><p><strong>How does they differ from each other?</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/522/1*h0XYfsMEGcdYbwG4kwXt4w.png" /></figure><p><strong>Can we use both together?</strong></p><p>Yes, we can use both ‘export default’ and ‘named export’ together.</p><p>Example:</p><p>Module1.mjs:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/531/1*2zlkIFxNaMAdITBnxIoVhw.png" /></figure><p>Module2.mjs:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/895/1*GhCBvzLpgTu4lrr0QkXSuA.png" /></figure><p>Terminal:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/920/1*nrRaqBoy3AeLlp1spX1-Bg.png" /></figure><p>Now, let’s talk about the “Props”….!</p><p><strong>What are Props?</strong></p><p>Props = Properties. In simple words: Props are used to pass data from one component to another in React.</p><p>Think like:</p><p>· Function arguments</p><p>· Input to a component</p><p><strong>Why Props are needed?</strong></p><p>Without props:</p><p>· Every component shows same data</p><p>· No flexibility</p><p>With props:</p><p>· We can send different data to same component</p><p>Example: a basic example without props (using no extra file)</p><p>App.js:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*dTvDwBiYT-VdFVrtO9QSzw.png" /></figure><p>Terminal:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*L8PY0WmEihfePUnhPeDlsw.png" /></figure><p>Output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*DLDSJtqAjgf91L9xEtTfqA.png" /></figure><p>Now, the same example using the props:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/808/1*_vouVRt5BS8KU6o-IrweaA.png" /></figure><p>Output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*ByFxj6TlchLnbgiJB0jpZw.png" /></figure><p><strong>Can we use props to pass other datatypes except string?</strong></p><p>Yes, we can do so.</p><p>· String → “text”</p><p>· Number → {20}</p><p>Example:</p><p>App.js:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*T3JaplBdhlNyJCMlO8hvNQ.png" /></figure><p>Output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*gcx1Ze5cRD1nUUvtr4-pOA.png" /></figure><p><strong>What if the default behaviour of props?</strong></p><p>App.js: (here we just emptied the passed value, it is not default behaviour example)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*hRmFviz2uVk30mtblTdA5Q.png" /></figure><p>Output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*OTa5_M3DCr4OXrGnlhB6HA.png" /></figure><p>Example: default behaviour. Props have no built-in default values. If missing → undefined.</p><p>App.js:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*0WS2ryJ_0HOeMM60n_N8Bg.png" /></figure><p>Output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*x6n6iV1K7xhmWfeggS8h4w.png" /></figure><p><strong>How to handle the missing prop of above example?</strong></p><p>We can use default props to do so.</p><p>Example:</p><p>App.js: (modern way)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*_CH9zQkMjmBPPR9QfW8vyA.png" /></figure><p>Output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/719/1*fEz5bhpsX0AcT-yPX8ZJDA.png" /></figure><p>Example: Default inside function body</p><p>App.js:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*vHt-AOCvlXzdb3MbUVTLCg.png" /></figure><p>Output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/719/1*fEz5bhpsX0AcT-yPX8ZJDA.png" /></figure><p>Example: defaultProps (older approach)</p><p>App.js:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*7jIFkHidsP0Xw7HAxVanyw.png" /></figure><p>Output:</p><p>Discouraged</p><p>Now, let’s understand about passing JSX with props:</p><p><strong>How to pass HTML code via JSX?</strong></p><p>children is the recommended React pattern for passing markup from a parent component to a child component.</p><p>Example:</p><p>Sample.jsx:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*V8bndtZHjE2VF_gP083FGQ.png" /></figure><p>App.jsx:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*00rFfQ-33HayS2bCDKRRww.png" /></figure><p>Output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*m7W8uFFUFIpTJnXTbHcmdg.png" /></figure><p>Now, suppose we want to make the colour of the text dynamic as well:</p><p>App.jsx:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*gxu3EKe124W3fQDm8xJ6nw.png" /></figure><p>In this code, the App component renders the Sample component twice. The first Sample receives a color prop with the value “Pink” and displays the heading <strong>“Hello, Aditya”</strong> as its children, so the text appears in pink. The second Sample is rendered without a color prop and displays <strong>“Hello, Utsav”</strong> as its children. Since both headings are passed between the opening and closing &lt;Sample&gt; tags, they are received through the children prop and rendered inside the &lt;div&gt; defined in the Sample component. This demonstrates how React components can be reused with different content and props to produce different outputs.</p><p>Sample..jsx:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*SnkutehwexmorKqltWyWKA.png" /></figure><p>Sample is a reusable React functional component that accepts two props: children and color. The children prop represents any JSX content placed between the &lt;Sample&gt; opening and closing tags when the component is used, and it is rendered inside the &lt;div&gt;. The color prop is used to dynamically set the text color through inline styling. The component also applies a fixed green border and a width of 300px, making it a simple wrapper that can display different content and text colors based on the props passed to it.</p><p>Output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*bc59Ofmzp1be1vEqrLNfEQ.png" /></figure><p>Now, suppose we want to make <strong>Get Input Field Value, </strong>I meant suppose we want to see the text user entered dynamically below the text box.</p><p>App.jsx:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*nlMTCRJldMSftc89dwe25g.png" /></figure><p>Output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/784/1*BOT3rTr0BQi06qwfNX1yUg.png" /></figure><p>Output: when we begin typing in the box</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/807/1*kF3P8ohgyda8NWktBt7aTQ.png" /></figure><p>This code demonstrates how to use React’s useState hook to capture and display the value entered into an input field. The state variable val is initialized with “Aditya”. Whenever the user types in the input box, the onChange event is triggered, and setVal(event.target.value) updates the state with the current input value. Since React re-renders the component whenever state changes, the &lt;h1&gt;{val}&lt;/h1&gt; element immediately displays the latest text entered by the user. This creates a real-time connection between the input field and the displayed value, a pattern known as a <strong>controlled component</strong> in React.</p><p>Now, suppose we want that the value in both the input field and the text displayed below it get deleted when we click on “clear” button, then we can use this:</p><p>App.jsx:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*_u3f2vD8ECHD41xa0oWxwA.png" /></figure><p>Output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/714/1*kMFigSzy56ALC5elIgDvSQ.png" /></figure><p>Output: when clicked on the button</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/719/1*Z6__ue3ftk7ahtas6qOF-A.png" /></figure><p><strong>Understanding Controlled Componenta:</strong></p><p><strong>What are Controlled Components?</strong></p><p>A controlled component in React is a form element (such as an &lt;input&gt;, &lt;textarea&gt;, or &lt;select&gt;) whose value is controlled by React state rather than the DOM itself.</p><p>Example:</p><p>App.jsx:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*m4s_Oyi5TvRIpvbVa6arWA.png" /></figure><p>Output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/677/1*CKPIdS_9RjG2G6qijVkJfg.png" /></figure><p>Output: when started typing something</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/676/1*IhSQwhdEupW3XlssG2CEPw.png" /></figure><p>How it works</p><p>1. The input’s value is stored in React state (val).</p><p>2. The value attribute is linked to that state.</p><p>3. When the user types, onChange updates the state.</p><p>4. React re-renders the input with the updated value.</p><p>This means React is the single source of truth for the input value.</p><p><strong>What are Uncontrolled Components?</strong></p><p>An uncontrolled component is a form element whose value is managed by the DOM itself instead of React state. React does not track the input value on every keystroke. Instead, you access the value only when needed, typically using a ref.</p><p>In other words:</p><p>· Controlled Component → React state controls the input value.</p><p>· Uncontrolled Component → The DOM controls the input value.</p><p>App.jsx:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*ro8bXBdVVfDMaKhRg8pC8g.png" /></figure><p>Output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/854/1*TMGY2AuMzh0t_LZ699IvWQ.png" /></figure><p>Output: when typed something and clicked on the “Get Value” button.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*cn5tYPKlqq2srZcQ8mTyMA.png" /></figure><p>How It Works</p><p>1. useRef() creates a reference to the input element.</p><p>2. The input stores its own value in the DOM.</p><p>3. React does not update state when the user types.</p><p>4. When the button is clicked, inputRef.current.value retrieves the current value from the DOM.</p><p>When to Use Uncontrolled Components</p><p>· Simple forms with minimal validation.</p><p>· Integrating with non-React libraries.</p><p>· File inputs (&lt;input type=”file”&gt;), which are commonly handled as uncontrolled components.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/771/1*nppl_PWdVyWMiu7HUjAbPg.png" /></figure><p><strong>Understanding State &amp; Handling Events in React :</strong></p><p>First understand about the Hooks.</p><p><strong>What are Hooks?</strong></p><p>In React, Hooks are special functions that let you use state and other React features in functional components (without writing class components).</p><p>In brief:</p><p>· <strong>useState</strong> → lets you add and manage state</p><p>· <strong>useEffect</strong> → handles side effects (like API calls, timers)</p><p>· <strong>useContext</strong> → shares data across components easily</p><p><strong>What is State in React?</strong></p><p>State is data inside a component that can change over time.</p><p><strong>Why do we need State?</strong></p><p>Without state:</p><p>· UI is static</p><p>· No updates happen</p><p>With state:</p><p>· UI updates automatically when data changes</p><p>Example: a basic example without the useState.</p><p>App.js:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/708/1*UQzlxCdk7VknvsCIsGey3g.png" /></figure><p>Output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*H8NJrtRDw5s4Gx0Ym0z4wg.png" /></figure><p>Now, suppose I want that there be a button and when someone clicks on that button the name of the fruit will get changed. For this, we will definitely need a function, and the button.</p><p>App.js:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*HnNT4WY982BCC0lC42Owmg.png" /></figure><p>Output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*B039Q5jFCVKZR7xh18P86w.png" /></figure><p>Output: when button was clicked.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*B039Q5jFCVKZR7xh18P86w.png" /></figure><p>But, why this doesn’t worked? Like, we have given the function, said that when this function is used, the value of fruit to be changed to the banana, but still Apple is reflected. Why?</p><p>ReactJS shows the update on the UI only when its component get re-rendered.</p><p>Now, To prove that value is updated but not reflected in the UI we will console the updated value.</p><p>App.js:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*BfZL8L_tVAT5egVOy5CA7g.png" /></figure><p>Output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*kLs1eTcPHU4115TkUPqsqQ.png" /></figure><p>Clearly, in console it says that function was called, and value of fruit is updated from Apple to Banana and reflected in console, but not in the UI.</p><p>So, how to overcome this? We will use State.</p><p>Let’s talk about ‘state’ again.</p><p><strong>What is State?</strong></p><p><strong>State in React:</strong></p><p>· State is a built-in feature used to store and manage data inside a component.</p><p>· It is mutable, meaning it can change over time.</p><p>· When state changes, React automatically re-renders the component to update the UI.</p><p>· In functional components, state is managed using the useState hook.</p><p>Example:</p><p><em>const [count, setCount] = useState(0);</em></p><p>Here:</p><p>· count → current state value</p><p>· setCount → function used to update state</p><p>· useState(0) → initial value is 0</p><p><strong>How does state differ from variable?</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/375/1*ADzZ_CBHhXwefUfV7SA9fw.png" /></figure><p><strong>How to import the state?</strong></p><p>In React, we don’t import “state” directly. Instead, we import the Hook called useState from React. Correct way:</p><p><em>import { useState } from “react”;</em></p><p>Example: using useState for that example of updating the fruit name. We are still not updating.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/895/1*Y4IFCoJn0IFoZ-SF9ZJdyg.png" /></figure><p>Output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/881/1*TBfNJtTLN0hKlQL0OXIkkA.png" /></figure><p><strong>Does useState always returns an array?</strong></p><p>Yes, useState always returns an array in React. What it returns:</p><p>· Current state value</p><p>· Function to update that state</p><p>Now, we will implement the part of button.</p><p>App.js:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*TAZxVfqn4WCZgnrCCA5PFg.png" /></figure><p>Output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*C0TMGzGXKjAq4yWriZ_D1A.png" /></figure><p>Output: when clicked.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*259s6iQBCxZHjXUCRpRdRA.png" /></figure><p>In this React code, useState(“Apple”) creates a state variable fruit with the initial value “Apple” and a function setFruit to update it. When the button is clicked, the handleFruit function runs and calls setFruit(“Banana”), which changes the state from “Apple” to “Banana”. As soon as the state updates, React automatically re-renders the component, so the updated value is shown on the screen.</p><p>Now, we will see the example of counter.</p><p>Counter.js: (no update logic)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*FZewIzWwHlK_eLfKJmYP1Q.png" /></figure><p>Output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/677/1*kNiyEhdySLbAaA568pyjDg.png" /></figure><p>Now, writing the update logic.</p><p>Counter.js:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*UkFrpk6_J1mxNfRpaJ09nA.png" /></figure><p>Output: initially</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/711/1*0tKXwF1LDVjA81hJ4NI7Cw.png" /></figure><p>Output: when clicked</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/698/1*Tylww5tbSaIno2sHOmJ9Uw.png" /></figure><p>Now, we are writing the same update the counter logic, but this time as a separate function.</p><p>Counter.js:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*e2G9wppzcNOk_uU6OOR7rA.png" /></figure><p>Output: at start</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/628/1*gcVG-ThBw8WBRaS871vTxw.png" /></figure><p>Output: when button was clicked.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/741/1*8aPqRNgzSYTqjPLsiyjUUQ.png" /></figure><p>Now, we can even use two states in the same code. We will see that in the counter example as well, where the other one be to count in reverse.</p><p>App.js:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*L86WiN8KzASb699p0FMLEQ.png" /></figure><p>Output: at start</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/530/1*qEqYiPvX6wL966bA0eLPpQ.png" /></figure><p>Output: when clicked.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/616/1*0e_kcpYLFi5Ty4RdQ4VLLQ.png" /></figure><p>This React component uses two state variables: count initialized to 0 and rcount initialized to 10. Clicking the first button increases count by 1, while clicking the second button decreases rcount by 1 using their respective state update functions. Whenever state changes, React automatically re-renders the component and updates the UI with the new values.</p><p>Example: using useState to change the status of the text from “On” to “off”.</p><p>LightSwitch.js:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*biBLvf6JAnsSJGCqE0_gQA.png" /></figure><p>Output: at start</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/825/1*C0GE3r8YAx_1cTufrH2ZNA.png" /></figure><p>Output: when button was clicked.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/1*K20gbFeZlrxI6ASRCenc1g.png" /></figure><p>This React component creates a simple light switch using the useState Hook. The variable isOn stores whether the light is currently ON (true) or OFF (false), and it starts as false, meaning the light is initially OFF. When the button is clicked, the toggleLight function runs and changes the state to the opposite value using !isOn (true becomes false, and false becomes true). The &lt;h1&gt; element displays “On” when isOn is true and “off” when it is false. React automatically re-renders the component whenever the state changes, so the displayed status updates instantly when the button is clicked.</p><p>Example: using useState to Show/Hide Text Component.</p><p>ShowHideText.js:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*ht1ZsFOcyuUxc4j6VYfeIQ.png" /></figure><p>Output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/491/1*kgX_1jJtr-caJU2xWJGbNg.png" /></figure><p>Output: when clicked</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/591/1*n9Wl9HzwqKJ9MhH3PvCmhQ.png" /></figure><p>It uses useState to store a value called show, which starts as true, meaning the text is visible at the beginning. When the button is clicked, the toggleText function runs and changes show to the opposite value using !show (so true becomes false and false becomes true). The button text also changes dynamically — showing “Hide” when the text is visible and “Show” when it is hidden. Finally, the paragraph is displayed only when show is true using show &amp;&amp; &lt;p&gt;…&lt;/p&gt;, so clicking the button hides and shows the message instantly without reloading the page.</p><p>Example: to capitalise the text entered by the user.</p><p>CapitalizeText.js:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*gRcX_Lo2w8cH1entdiup8g.png" /></figure><p>Output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/778/1*0o86oWuukVco2z2CT9iRCA.png" /></figure><p>Output: when something was typed and button was clicked.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/863/1*F8k5zL85iIrfgkQYOL19zQ.png" /></figure><p>This code defines a controlled component in React that manages user input and performs a string transformation. By invoking the useState hook, it initializes a state variable (text) and its corresponding setter function (captext). The &lt;input&gt; element is bound to this state via its value attribute, creating a one-way data binding from state to view. To achieve two-way data binding, an onChange event handler captures user input events, extracting the real-time value via e.target.value and updating the state, which triggers a component re-render. When the button is clicked, it executes the cap event handler, which utilizes the JavaScript toUpperCase() prototype method to transform the current state string and commits the mutated, capitalized string back to the state, causing the DOM to update with the final capitalized text.</p><p>Example: using useState to change the theme from light to dark and viceversa.</p><p>ToggleMode.js:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*Rk5ZlRtcQ0mIE91G1GEbzA.png" /></figure><p>Output: by default</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*9ehEmcYX8C0DoP0_jqUVOQ.png" /></figure><p>Output: when button was clicked.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*oXu5aUBp53JWvlDDzGMRnQ.png" /></figure><p>This code builds a webpage that flips between light and dark themes when you click a button. Inside the component, a boolean (true/false) memory switch called mode is created using useState(false). When the button is clicked, it runs the changeMode function, which simply flips that switch to its opposite value. Because the styles of the page and the text on the screen are tied directly to this switch using conditional shortcuts, the entire background color and text instantly swap from light to dark (or dark to light) every time the button is pressed.</p><p>Now, keep in mind these things about the component:</p><p>App.js: (We can have more than one component in a file, and we can use one component inside another by calling it. The component we export (App) becomes the main component available outside the file.)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*rFJPV10g9h_KmnPpu84Fzg.png" /></figure><p>Output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/767/1*Y-baF_e1S1Q96pVw7ndzvA.png" /></figure><p>In this code, App is the main component that is exported and rendered. Inside App, an &lt;h1&gt; heading and the Greeting component are displayed. The Greeting component is another component in the same file that returns an &lt;h2&gt; heading. When App renders, it also renders Greeting, so both headings appear on the screen. The empty tags (&lt;&gt; &lt;/&gt;) are React Fragments, which let us group multiple elements without adding an extra HTML element.</p><p>Also, keep in mind that we can do like this in JSX:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*4nI3A_321eSrwLhdxu1rsg.png" /></figure><p>Output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/609/1*AgA9xKPtsGbaDlrelf-MBg.png" /></figure><p>Also, keep in mind that we can use the functions inside the component.</p><p>App.js:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*tS4Hvct0c66f0Ny1Z-2LYQ.png" /></figure><p>Output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/616/1*o2TUK-038x6UBa7kMas48w.png" /></figure><p>Now, let’s understand how to handle the checkboxes in react:</p><p>App.jsx:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*PJBuZo4DWvLFFZE1FZIMlg.png" /></figure><p>Output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*07GQMbsZm8b_w-LLsBt0rg.png" /></figure><p>Output: when clicked on the check boxes</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*jUyM0AA771ILqKGOaSOLJA.png" /></figure><p>This React component lets users select multiple skills using checkboxes. The skills state stores all selected skills in an array. When a checkbox is checked or unchecked, the handleSkills function runs and gets the checkbox’s value (e.g., “PHP”) and checked status (true or false). If checked, the skill is added to the skills array using the spread operator (…skills); if unchecked, it is removed using filter(). Finally, skills.join(“, “) displays all selected skills as a comma-separated list on the screen.</p><p>Now, let’s understand how to handle the radio buttons in react:</p><p>App.jsx:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*bQQwuTwplqBBs0vSbvFsQg.png" /></figure><p>Output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*VIJheH6Elf6DrlpRWm7S1A.png" /></figure><p>Output: when clicked on the other radio button.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*2ceV5F_kCAMH_WPhrwAH-Q.png" /></figure><p>This React code creates a simple gender selection form using radio buttons. It uses the useState hook to store the selected gender, with “male” set as the default value. When the user clicks either the Male or Female radio button, the onChange event updates the gender state with the selected value. The checked property ensures that the correct radio button remains selected based on the current state. Finally, the selected gender is displayed on the screen in real time below the radio buttons.</p><p><strong>Loop in JSX with Map function:</strong></p><p>App.jsx:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*4Eq1_S_0xvTgzwnbTW324g.png" /></figure><p>Output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/681/1*LSsk3RFFtkSSn6T1Bg6POA.png" /></figure><p><strong>Contact Me</strong><br>📧 <strong>Email:</strong> adii.utsav@gmail.com<br>🔗 <strong>LinkedIn:</strong> <a href="https://www.linkedin.com/in/aditya-kumar-3241b6286/">https://www.linkedin.com/in/aditya-kumar-3241b6286/</a><br>💻 <strong>GitHub:</strong> <a href="https://github.com/Rememberful">https://github.com/Rememberful</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d5a25ef7ce98" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ReactJS — Part 1]]></title>
            <link>https://medium.com/@adii.utsav/reactjs-part-1-44d067b0adfd?source=rss-f1d05be749b2------2</link>
            <guid isPermaLink="false">https://medium.com/p/44d067b0adfd</guid>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[part-1]]></category>
            <category><![CDATA[reactjs]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[mern-stack]]></category>
            <dc:creator><![CDATA[Aditya Kumar]]></dc:creator>
            <pubDate>Thu, 16 Jul 2026 05:53:51 GMT</pubDate>
            <atom:updated>2026-07-16T05:53:51.513Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_5m_npH7QHZJT80zCBI-pA.jpeg" /></figure><p><strong>Introduction To ReactJS:</strong></p><p><strong>What is ReactJS?</strong></p><p>ReactJS is a JavaScript library developed by Meta used for building fast and interactive user interfaces using reusable components.</p><p><strong>Why Developers Like React?</strong></p><p>1. Reusable code (as it is component based)</p><p>2. Faster websites (because of Virtual DOM)</p><p>3. Easy to Manage Large Projects</p><p><strong>React vs Normal JavaScript</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/527/1*zRJZsZqcXjNEgp0Iook5GA.png" /></figure><p><strong>Creating our first react app using create-react-app:</strong></p><p><em>npx create-react-app my-app</em></p><p><strong>What is npx?</strong></p><p>npx is a tool that comes with Node.js.</p><p>It allows you to:</p><p>· Run packages directly</p><p>· Without installing them globally</p><p><strong>What is create-react-app?</strong></p><p>create-react-app is a tool made to quickly create a React project with all setup already done.</p><p>Without it, you would manually configure:</p><p>· Webpack</p><p>· Babel</p><p>· Dependencies</p><p>· Folder structure</p><p>This tool does everything automatically.</p><p><strong>What is my-app?</strong></p><p>This is your project name.</p><p><strong>What we get at the end in the folder?</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/962/1*9Ai9BqV2qMAGXtsRUmgfgg.png" /></figure><p><strong>Exploring the ‘public’ folder:</strong></p><p>Here the most important file is the “index.html”, rest can be ignored. We don’t modify the index.html even.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*I2Aal-r-A161KpXFAYrqfg.png" /></figure><p><strong>How to run the react app?</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/925/1*bFf-hPxWJDdSuz4MFpTmNg.png" /></figure><p>Output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*r3xpJjUO7Gv7lqmMPC75aw.png" /></figure><p><strong>Understanding JSX</strong></p><p><strong>What is JSX?</strong></p><p>JSX is a syntax used in React to write UI code in an HTML-like way inside JavaScript. It allows us to write:</p><p>· HTML-like code</p><p>· Inside JavaScript</p><p>Example:</p><p><em>const element = &lt;h1&gt;Hello React&lt;/h1&gt;;</em></p><p><strong>Is JSX same as HTML?</strong></p><p>JSX looks like HTML, but:</p><p>· It is actually JavaScript</p><p>· Browser does not understand JSX directly</p><p>· React converts JSX into JavaScript</p><p>This conversion is done by:</p><p>· Babel (behind the scenes)</p><p><strong>Why JSX is Useful?</strong></p><p>1. Easier to read</p><p>2. Easier to write UI</p><p>3. JS + HTML together</p><p>Example: a basic example of JSX.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/783/1*MHnjLi8eqDpufie4rOxd0g.png" /></figure><p>Here the App() is component, while &lt;div&gt; is JSX and, return() returns UI.</p><p><strong>JSX rules:</strong></p><p>Rule1: Return Only One Parent Element. Below example is correct as the &lt;div&gt; is the only one which is returned (discussed later in details)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*HV8cxD-_gxWOWU-ECePZGg.png" /></figure><p>Rule2: Every Tag Must Be Closed</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*MLr3ykkeQAUo4A07E8Xtfg.png" /></figure><p>Here the &lt;img&gt; tag is closed, while the &lt;br&gt; tag is not closed. If uncommented, it will show error.</p><p>Rule 3: Use className Instead of class</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/601/1*ync3hepyRkQwtBIPYhaWZg.png" /></figure><p>Rule 4: JavaScript Inside {} JSX allows JavaScript using curly braces.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*B1N0MXYIpuBJamJ9y7pqvw.png" /></figure><p>Output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*yidUUswSYR1Q1SOzt1TU9w.png" /></figure><p><strong>What is a Fragment?</strong></p><p>A Fragment is used to: Group multiple JSX elements without adding an extra HTML tag to the browser.</p><p>Without the &lt;&gt; &lt;/&gt; (React Fragments):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*dL2gxUXW4Sk_31_85b6O2g.png" /></figure><p>Output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/886/1*5Ts6ZdQkir5zgfh83SK61Q.png" /></figure><p>In JSX, we must return: <strong>Only one parent element.</strong></p><p>So, this is right:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*dL2gxUXW4Sk_31_85b6O2g.png" /></figure><p>While this is wrong: Error happens because React expects one root element.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*6_0VH-NmaNuVGl5RomqWag.png" /></figure><p><strong>How to deal with the above error?</strong></p><p>Either you can make sure that only one root element is returned (by using one parent &lt;div&gt; or use the Fragments.</p><p>Example: using the parent &lt;div&gt;</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*HV8cxD-_gxWOWU-ECePZGg.png" /></figure><p>Output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*XSDcy8OBy98E2DYytF-aYg.png" /></figure><p>Example: using the fragments.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*QkGE2eL7ajQLpJxzVl6nKA.png" /></figure><p>Output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/788/1*zz8E6BP6tFtrFU8lyl0l6Q.png" /></figure><p><strong>Setup + Adding Bootstrap to React:</strong></p><p>Let’s first understand about the types of page applications. By this we meant about the: Single Page Application (SPA) and Multi page application (MPA).</p><p><strong>What is SPA?</strong></p><p>A Single Page Application means: The website has only ONE HTML page, and content changes dynamically without full page reload.</p><p>Example: Gmail, Netflix, Instagram.</p><p><strong>How SPA works?</strong></p><p>When you open a SPA:</p><p>1. Browser loads one HTML file</p><p>2. React loads JavaScript</p><p>3. React controls the entire UI</p><p>4. When you click something:</p><p>· Only part of the page updates</p><p>· Page does NOT reload</p><p><strong>Why SPA is Fast?</strong></p><p>Because:</p><p>· Only required data changes</p><p>· No full page refresh</p><p>· Less network usage</p><p>Important File in SPA: public/index.html (This is the <strong>ONLY HTML file</strong> in React SPA. Everything else is JavaScript.)</p><p><strong>What is MPA?</strong></p><p>A Multi Page Application means: Every page is a separate HTML file, and browser reloads the page every time.</p><p>Examples: traditional websites, blogs, government websites.</p><p><strong>How MPA Works?</strong></p><p>When you click a link:</p><p><em>Home.html → reload → About.html → reload → Contact.html</em></p><p>Each page:</p><p>· Sends new request to server</p><p>· Loads full HTML again</p><p><strong>Why MPA is Slower?</strong></p><p>Because:</p><p>· Full page reload every time</p><p>· More server requests</p><p>· More loading time</p><p><strong>SPA vs MPA:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/486/1*fMLqwMJESZ__V_XIUsp-KQ.png" /></figure><p>Now, let’s talk about the Node Modules folder:</p><p><strong>What is node_modules folder?</strong></p><p>node_modules is a folder that contains all installed packages (libraries) used in your project.</p><p><strong>What is inside node_modules?</strong></p><p>It contains:</p><p>· React library</p><p>· React DOM</p><p>· Babel tools</p><p>· Webpack tools</p><p>· Other dependencies</p><p>· Sub-dependencies (dependencies of dependencies)</p><p><strong>Why node_modules folder is so big?</strong></p><p>Because:</p><p>· Each library depends on other libraries</p><p>· All dependencies are installed locally</p><p>That’s why it becomes very large.</p><p><strong>Why we don’t upload node_modules to GitHub?</strong></p><p>Because:</p><p>· Very large (MBs to GBs)</p><p>· Can be recreated using package.json</p><p><strong>Can we delete the node modules folder?</strong></p><p>Yes, we can.</p><p><strong>How to install node_modules folder again if got deleted?</strong></p><p>Using the following command:</p><p><em>npm install</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/739/1*04UA1RRTrp1Zhd0-WkRsTg.png" /></figure><p>Now, let’s talk about BootStrap in React.</p><p><strong>What is Bootstrap?</strong></p><p>Bootstrap is a CSS framework that gives you:</p><p>· Ready-made styles</p><p>· Buttons</p><p>· Forms</p><p>· Navbar</p><p>· Grid system</p><p>Instead of writing CSS from scratch, you use prebuilt classes.</p><p><strong>Where can we find this?</strong></p><p>Website: <a href="https://getbootstrap.com/">https://getbootstrap.com/</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*JC1ToYKlN8emmD8SJjMQDQ.png" /></figure><p><strong>How to include this BootStrap in our project?</strong></p><p>Visit the docs:</p><p><a href="https://getbootstrap.com/docs/5.3/getting-started/introduction/">Get started with Bootstrap</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*NzrriiL9q95gUKT0_BhOHw.png" /></figure><p>Using the CDN link:</p><p><a href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.8/dist/js/bootstrap.bundle.min.js">https://cdn.jsdelivr.net/npm/bootstrap@5.3.8/dist/js/bootstrap.bundle.min.js</a></p><p><a href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.8/dist/css/bootstrap.min.css">https://cdn.jsdelivr.net/npm/bootstrap@5.3.8/dist/css/bootstrap.min.css</a></p><p><strong>Where to paste this link?</strong></p><p>Inside the index.html of the public folder, as shown below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/597/1*gx63-8284rxmRbzblrgkjQ.png" /></figure><p><strong>Why index.html?</strong></p><p>Because for the SPA, in react index.html is the only page which will be loading every time.</p><p>Before pasting the link:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*o8y6VawGTh8-q_a_GoKNAQ.png" /></figure><p>After pasting the link:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*KkNvogvuNgn9JfNgVxrW_w.png" /></figure><p>Now, let’s do something in the code to see the implementation of them practically.</p><p>As usual we will work on the App.js:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*3wXVFM97JO1KF2TQ0Z7NyQ.png" /></figure><p>Output: (don’t forget to do ‘npm start’)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*Z25MdTGgFH44f2KMhnUz0A.png" /></figure><p><strong>What is the difference between JS function call and React function call:</strong></p><p>· JS function → you call it anytime, it runs immediately.</p><p>· React component function → React calls it during render to build UI, and may re-call it on state/props changes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/767/1*oblWqHbuqX1GorR_NkhFhQ.png" /></figure><p><strong>How to pass functions to the button for onClick event?</strong></p><p>App.js:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*tEwbayUZAOhURWSJ9ghMMA.png" /></figure><p>Output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*4mEs4vP0Ade-OfxiP4yKqw.png" /></figure><p>When clicked on button:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*ZoHLCE6M_GJu4NMpTAxYQg.png" /></figure><p>Basically, Always pass a function reference, not a function call.</p><p>Wrong way:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*GXB_jWaUCuTwcBBDfFe2SA.png" /></figure><p>Output:</p><p>Not worked as expected.</p><p><strong>Contact Me</strong><br>📧 <strong>Email:</strong> adii.utsav@gmail.com<br>🔗 <strong>LinkedIn:</strong> <a href="https://www.linkedin.com/in/aditya-kumar-3241b6286/">https://www.linkedin.com/in/aditya-kumar-3241b6286/</a><br>💻 <strong>GitHub:</strong> <a href="https://github.com/Rememberful">https://github.com/Rememberful</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=44d067b0adfd" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[I Built a Production-Ready Secure Notes App From Scratch — Here’s Everything I Learned]]></title>
            <link>https://medium.com/@adii.utsav/i-built-a-production-ready-secure-notes-app-from-scratch-heres-everything-i-learned-e4a1fd147129?source=rss-f1d05be749b2------2</link>
            <guid isPermaLink="false">https://medium.com/p/e4a1fd147129</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[full-stack]]></category>
            <category><![CDATA[owasp]]></category>
            <category><![CDATA[web-development]]></category>
            <dc:creator><![CDATA[Aditya Kumar]]></dc:creator>
            <pubDate>Fri, 10 Jul 2026 01:01:01 GMT</pubDate>
            <atom:updated>2026-07-10T01:01:01.409Z</atom:updated>
            <content:encoded><![CDATA[<p>From a plain textarea to a full-stack OWASP-hardened app with Google Sign-In, rich text editing, full-text search, and auto-save.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ee3zpovQaynp9CgcIh6L3A.png" /><figcaption>Screenshot of the notes dashboard</figcaption></figure><p>I recently built a full-stack notes application that I’m genuinely proud of. Not because it does something novel — notes apps are everywhere — but because of how it’s built. Every decision was deliberate: the database schema, the security layer, the way content is stored, how files are handled, even how the app behaves when the server is asleep. This article covers everything. The tech choices, the tricky problems, the bugs I caught before they shipped, and the engineering decisions I’d defend in an interview. I’ll share real code throughout.</p><p>Live demo: <a href="https://notes-frontend-j8qo.onrender.com/login">notes-frontend-j8qo.onrender.com</a></p><p>GitHub: <a href="https://github.com/Rememberful/Secured-notetaking.git">github.com/Rememberful/secured-messaging</a>.</p><p><strong>The Stack:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/618/1*htwMh0M7Re4YBqXCKzi4KQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/628/1*Yq3TdMa1uphuTK-06uHtWw.png" /></figure><h3><strong>Part 1: Starting with a Solid Foundation</strong></h3><p>The Database Schema Before writing a single route, I designed the schema. Every engineering decision flows from here</p><pre>-- Users — supports both email/password and Google Sign-In<br>CREATE TABLE users (<br>  id SERIAL PRIMARY KEY,<br>  email TEXT UNIQUE NOT NULL,<br>  name TEXT,<br>  password_hash TEXT,        -- NULL for Google-only accounts<br>  google_id TEXT UNIQUE,     -- NULL for password-only accounts<br>  created_at TIMESTAMPTZ NOT NULL DEFAULT now()<br>);<br><br>-- Notes — content stored as Tiptap JSON<br>CREATE TABLE notes (<br>  id SERIAL PRIMARY KEY,<br>  user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,<br>  title TEXT NOT NULL,<br>  content TEXT NOT NULL DEFAULT &#39;&#39;,<br>  -- Generated column: Postgres maintains this automatically on every INSERT/UPDATE<br>  -- Weight A = title (ranks higher), Weight B = content<br>  search_vector tsvector GENERATED ALWAYS AS (<br>    setweight(to_tsvector(&#39;english&#39;, coalesce(title, &#39;&#39;)), &#39;A&#39;) ||<br>    setweight(to_tsvector(&#39;english&#39;, coalesce(content, &#39;&#39;)), &#39;B&#39;)<br>  ) STORED,<br>  created_at TIMESTAMPTZ NOT NULL DEFAULT now(),<br>  updated_at TIMESTAMPTZ NOT NULL DEFAULT now()<br>);<br><br>-- GIN index makes full-text search fast at scale<br>CREATE INDEX idx_notes_search_vector ON notes USING GIN (search_vector);<br><br>-- Tags: many-to-many, scoped per user<br>CREATE TABLE tags (<br>  id SERIAL PRIMARY KEY,<br>  user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,<br>  name TEXT NOT NULL,<br>  UNIQUE (user_id, name)<br>);<br><br>CREATE TABLE note_tags (<br>  note_id INTEGER NOT NULL REFERENCES notes(id) ON DELETE CASCADE,<br>  tag_id INTEGER NOT NULL REFERENCES tags(id) ON DELETE CASCADE,<br>  PRIMARY KEY (note_id, tag_id)<br>);<br><br>-- Media: images stored as bytea<br>CREATE TABLE media (<br>  id SERIAL PRIMARY KEY,<br>  note_id INTEGER NOT NULL REFERENCES notes(id) ON DELETE CASCADE,<br>  user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,<br>  filename TEXT NOT NULL,<br>  mime_type TEXT NOT NULL,<br>  size_bytes INTEGER NOT NULL CHECK (size_bytes &lt;= 2097152), -- 2MB DB-level hard cap<br>  data BYTEA NOT NULL,<br>  created_at TIMESTAMPTZ NOT NULL DEFAULT now()<br>);<br><br>-- Password reset tokens: hashed, single-use, expiring<br>CREATE TABLE password_reset_tokens (<br>  id SERIAL PRIMARY KEY,<br>  user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,<br>  token_hash TEXT NOT NULL,  -- SHA-256 hash of the raw token<br>  expires_at TIMESTAMPTZ NOT NULL,<br>  used_at TIMESTAMPTZ,       -- NULL until redeemed<br>  created_at TIMESTAMPTZ NOT NULL DEFAULT now()<br>);</pre><p>Three design decisions worth calling out:</p><ol><li>search_vector is a generated column. This is the most interesting one. Instead of maintaining the search index in application code (which is a bug waiting to happen — someone will forget to update it on PUT ), I let Postgres do it automatically. Every INSERT and UPDATE regenerates the tsvector from title and content , weighted so title matches rank higher. A GIN index makes it fast.</li><li>Tags are many-to-many with a proper join table — not a TEXT[] array column or a comma-separated string. Both of those are shortcuts that make filtering and counting painful later. A join table with cascade deletes is the right answer and it’s not significantly more complex.</li><li>password_hash and google_id are both nullable. A user who signed up via Google has no password_hash . A user who signed up with email/password has no google_id . If the same email signs in via Google later, we link them by setting google_id on the existing row.</li></ol><h3><strong>Part 2: Auth — Done Right</strong></h3><h4><strong>Email/Password with bcrypt</strong></h4><pre>// backend/src/routes/auth.js<br><br>router.post(&#39;/signup&#39;, signupLimiter, validateBody(signupSchema), async (req, res) =&gt; {<br>  const { email, password, name } = req.body;<br>  // email is already trimmed + lowercased by the zod schema<br>  <br>  const existing = await pool.query(&#39;SELECT id FROM users WHERE email = $1&#39;, [email]);<br>  if (existing.rows.length &gt; 0) {<br>    return res.status(409).json({ error: &#39;An account with that email already exists&#39; });<br>  }<br><br>  // Cost factor 12 — meaningfully more brute-force resistant than the default 10<br>  const passwordHash = await bcrypt.hash(password, 12);<br>  const result = await pool.query(<br>    &#39;INSERT INTO users (email, name, password_hash) VALUES ($1, $2, $3) RETURNING *&#39;,<br>    [email, name || null, passwordHash]<br>  );<br><br>  const token = issueToken(result.rows[0]);<br>  res.status(201).json({ token, user: publicUser(result.rows[0]) });<br>});</pre><p>The JWT carries issuer and audience claims, verified on every request:</p><pre>function issueToken(user) {<br>  return jwt.sign({ sub: user.id, email: user.email }, process.env.JWT_SECRET, {<br>    expiresIn: &#39;7d&#39;,<br>    issuer: &#39;notes-app&#39;,<br>    audience: &#39;notes-app-client&#39;,<br>  });<br>}</pre><p>Why does this matter? If the same `JWT_SECRET` were ever reused across services, a token signed for Service A couldn’t be used against Service B because the `audience` claim wouldn’t match. Defense in depth.</p><h3>Google Sign-In — Server-Side Verification</h3><p>This is the part most tutorials get wrong. They decode the JWT the browser sends from Google and trust it. Never do this. The correct flow:</p><ol><li>Browser shows Google’s button (via the GSI SDK)</li><li>User clicks — Google returns a signed credential token to the browser</li><li>Browser sends that raw token to your backend</li><li>Your backend verifies it against Google’s servers</li></ol><pre>router.post(&#39;/google&#39;, authAttemptLimiter, validateBody(googleAuthSchema), async (req, res) =&gt; {<br>  const { credential } = req.body;<br>  <br>  const ticket = await googleClient.verifyIdToken({<br>    idToken: credential,<br>    audience: process.env.GOOGLE_CLIENT_ID,  // Rejects tokens for other apps<br>  });<br>  const payload = ticket.getPayload();<br>  const { sub: googleId, email: rawEmail, name, email_verified } = payload;<br>  <br>  // Normalize email — Google can return mixed case<br>  const email = rawEmail.trim().toLowerCase();<br>  <br>  if (!email_verified) {<br>    return res.status(401).json({ error: &#39;Google account email is not verified&#39; });<br>  }<br>  <br>  // Find existing user or create new one<br>  let result = await pool.query(&#39;SELECT * FROM users WHERE google_id = $1&#39;, [googleId]);<br>  let user = result.rows[0];<br>  <br>  if (!user) {<br>    // Link to existing email/password account if emails match<br>    const existingResult = await pool.query(&#39;SELECT * FROM users WHERE email = $1&#39;, [email]);<br>    if (existingResult.rows[0]) {<br>      await pool.query(&#39;UPDATE users SET google_id = $1 WHERE id = $2&#39;, [googleId, existingResult.rows[0].id]);<br>      user = { ...existingResult.rows[0], google_id: googleId };<br>    } else {<br>      const insertResult = await pool.query(<br>        &#39;INSERT INTO users (email, name, google_id) VALUES ($1, $2, $3) RETURNING *&#39;,<br>        [email, name || null, googleId]<br>      );<br>      user = insertResult.rows[0];<br>    }<br>  }<br>  <br>  res.json({ token: issueToken(user), user: publicUser(user) });<br>});</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rG-AgV0kwIm3QjF8K5G6xw.png" /><figcaption>The login page showing both the email/password form and the “Continue with Google” button</figcaption></figure><h3><strong>Part 3: OWASP Top 10 — Actually Implementing It</strong></h3><p>Most projects say “we follow OWASP.” Let me show you what that actually looks like in code.</p><p><strong>Rate Limiting (API4 — Unrestricted Resource Consumption)</strong></p><pre>// backend/src/middleware/rateLimiters.js<br><br>export const authAttemptLimiter = rateLimit({<br>  windowMs: 15 * 60 * 1000,  // 15 minutes<br>  max: 10,                    // 10 attempts per IP<br>  message: { error: &#39;Too many attempts. Please try again in a few minutes.&#39; },<br>});<br><br>export const signupLimiter = rateLimit({<br>  windowMs: 60 * 60 * 1000,  // 1 hour<br>  max: 10,<br>  message: { error: &#39;Too many accounts created from this location.&#39; },<br>});</pre><p>I verified this actually works — hitting /api/auth/login 12 times in a row, the first 10 got 401 (wrong credentials), attempts 11 and 12 correctly got 429 . The app also needs app.set(‘trust proxy’, 1) — without it, all traffic behind Render’s load balancer looks like it comes from the same IP, making rate limiting useless.</p><p><strong>Input Validation + Mass Assignment Protection (API8, A03)</strong></p><pre>// backend/src/validation/schemas.js<br><br>export const noteCreateSchema = z.object({<br>  title: z.string().trim().min(1, &#39;Title is required&#39;).max(200),<br>  content: z.string().max(50000).optional().default(&#39;&#39;),<br>  tags: z.array(z.string().trim().max(40)).max(20).optional(),<br>});<br><br>export function validateBody(schema) {<br>  return (req, res, next) =&gt; {<br>    const result = schema.safeParse(req.body);<br>    if (!result.success) {<br>      return res.status(400).json({ error: result.error.errors[0]?.message });<br>    }<br>    req.body = result.data;  // Replace with parsed, coerced, trimmed data<br>    next();<br>  };<br>}</pre><p>The key insight: by parsing req.body through a strict schema and replacing it with only the fields defined in the schema, any extra fields an attacker sends (like user_id: 99999 to try to hijack another user’s note) are silently stripped. I tested this — posting { title: “test”, user_id: 99999 } created a note owned by the authenticated user, not user 99999</p><h4><strong>File Upload Security (A04 — Insecure Design)</strong></h4><p>Trusting the Content-Type header a browser sends on an upload is a classic mistake. It’s trivially spoofable — rename evil.html to photo.jpg and the header will say image/jpeg . I check the actual file bytes:</p><pre>function detectRealMimeType(buffer) {<br>  // JPEG: starts with FF D8 FF<br>  if (buffer[0] === 0xff &amp;&amp; buffer[1] === 0xd8 &amp;&amp; buffer[2] === 0xff) {<br>    return &#39;image/jpeg&#39;;<br>  }<br>  // PNG: starts with 89 50 4E 47 0D 0A 1A 0A<br>  if (<br>    buffer[0] === 0x89 &amp;&amp; buffer[1] === 0x50 &amp;&amp; buffer[2] === 0x4e &amp;&amp; buffer[3] === 0x47 &amp;&amp;<br>    buffer[4] === 0x0d &amp;&amp; buffer[5] === 0x0a &amp;&amp; buffer[6] === 0x1a &amp;&amp; buffer[7] === 0x0a<br>  ) {<br>    return &#39;image/png&#39;;<br>  }<br>  // GIF: starts with GIF87a or GIF89a<br>  if (<br>    buffer[0] === 0x47 &amp;&amp; buffer[1] === 0x49 &amp;&amp; buffer[2] === 0x46 &amp;&amp; buffer[3] === 0x38 &amp;&amp;<br>    (buffer[4] === 0x37 || buffer[4] === 0x39) &amp;&amp; buffer[5] === 0x61<br>  ) {<br>    return &#39;image/gif&#39;;<br>  }<br>  // WebP: RIFF....WEBP<br>  if (<br>    buffer[0] === 0x52 &amp;&amp; buffer[1] === 0x49 &amp;&amp; buffer[2] === 0x46 &amp;&amp; buffer[3] === 0x46 &amp;&amp;<br>    buffer[8] === 0x57 &amp;&amp; buffer[9] === 0x45 &amp;&amp; buffer[10] === 0x42 &amp;&amp; buffer[11] === 0x50<br>  ) {<br>    return &#39;image/webp&#39;;<br>  }<br>  return null;<br>}</pre><p>I tested this with a text file renamed to .png with a spoofed Content-Type: image/png header — it correctly got rejected with 415 Unsupported Media Type .</p><p><strong>Broken Object Level Authorization (API1)</strong></p><p>Every single note and media operation checks ownership:</p><pre>// Not just: SELECT * FROM notes WHERE id = $1<br>// Always: SELECT * FROM notes WHERE id = $1 AND user_id = $2<br><br>const result = await pool.query(<br>  &#39;SELECT * FROM notes WHERE id = $1 AND user_id = $2&#39;,<br>  [req.params.id, req.userId]  // req.userId comes from verified JWT<br>);<br>if (!result.rows[0]) return res.status(404).json({ error: &#39;Note not found&#39; });</pre><p>Returning 404 (not 403 ) for resources that belong to other users is intentional — it avoids confirming that the resource exists at all.</p><h3><strong>Part 4: Full-Text Search with Postgres</strong></h3><p>Most apps implement search with LIKE ‘%query%’ . This is slow, can’t rank results, and doesn’t understand language. Postgres has a built-in full-text search engine that’s genuinely good.</p><pre>// Search with relevance ranking<br>const result = await pool.query(<br>  `SELECT ${NOTE_COLUMNS}, ts_rank(n.search_vector, websearch_to_tsquery(&#39;english&#39;, $2)) AS rank<br>   FROM notes n<br>   WHERE n.user_id = $1<br>     AND n.search_vector @@ websearch_to_tsquery(&#39;english&#39;, $2)<br>   ORDER BY rank DESC, n.updated_at DESC`,<br>  [req.userId, query]<br>);</pre><p>websearch_to_tsquery handles natural language: deploy -production finds notes about deployment that don’t mention production. “exact phrase” finds exact matches. And it handles stemming — searching “deploying” finds notes containing “deploy”, “deployed”, “deployment”.</p><p>The @@ operator does the actual matching. ts_rank scores results — title matches (weight A) rank higher than content matches (weight B) because we weighted the tsvector that way in the schema.</p><p>The frontend debounces by 300ms so the API isn’t hit on every keystroke:</p><pre>// frontend/src/components/SearchBar.jsx<br>useEffect(() =&gt; {<br>  clearTimeout(debounceRef.current);<br>  debounceRef.current = setTimeout(() =&gt; {<br>    onSearch(value.trim());<br>  }, 300);<br>  return () =&gt; clearTimeout(debounceRef.current);<br>}, [value, onSearch]);</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WvUd4LDNjU5l_bE33ctaiQ.png" /><figcaption>The dashboard with the search bar active, showing filtered results for a search term.</figcaption></figure><h3><strong>Part 5: Rich Text Editing with Tiptap</strong></h3><p>The most common mistake here is trying to build a WYSIWYG editor from scratch. contentEditable , browser selection APIs, execCommand deprecation, and cross-browser inconsistencies make this a multimonth project. I used Tiptap, which sits on top of ProseMirror.</p><p>The key architectural decision: store content as Tiptap JSON, not HTML. HTML is fragile, hard to sanitize, and breaks when you update the editor version. JSON is structured, predictable, and serializes cleanly to the TEXT column in Postgres.</p><pre>// frontend/src/components/RichEditor.jsx<br><br>const editor = useEditor({<br>  extensions: [<br>    StarterKit.configure({<br>      strike: false,          // Using explicit extension instead<br>      heading: { levels: [1, 2] },<br>    }),<br>    Underline,<br>    Strike,<br>    Link.configure({<br>      openOnClick: readOnly,  // Only clickable when viewing, not editing<br>      HTMLAttributes: { rel: &#39;noopener noreferrer&#39;, target: &#39;_blank&#39; },<br>    }),<br>    Placeholder.configure({ placeholder }),<br>  ],<br>  content: normalizeContent(content),  // Handles legacy plain-text notes<br>  editable: !readOnly,<br>  onUpdate: ({ editor }) =&gt; {<br>    onChange?.(JSON.stringify(editor.getJSON()));<br>  },<br>});</pre><p>The normalizeContent function handles backwards compatibility — notes saved before the rich text editor was added were plain text strings. When loaded into Tiptap, they get wrapped in paragraph nodes automatically:</p><pre>function normalizeContent(raw) {<br>  if (!raw) return &#39;&#39;;<br>  try {<br>    const parsed = JSON.parse(raw);<br>    if (parsed?.type === &#39;doc&#39;) return parsed;  // Already Tiptap JSON<br>  } catch {}<br>  // Legacy plain text — wrap in paragraph nodes<br>  return {<br>    type: &#39;doc&#39;,<br>    content: raw.split(&#39;\n&#39;).map((line) =&gt; ({<br>      type: &#39;paragraph&#39;,<br>      content: line ? [{ type: &#39;text&#39;, text: line }] : [],<br>    })),<br>  };<br>}</pre><p>For the note card preview, I extract plain text from the Tiptap JSON and truncate to 20 words:</p><pre>// frontend/src/utils/richText.js<br><br>function extractText(node) {<br>  if (node.type === &#39;text&#39;) return node.text || &#39;&#39;;<br>  if (!node.content) return &#39;&#39;;<br>  return node.content.map(extractText).join(&#39; &#39;);<br>}<br><br>export function getPreviewText(raw, wordLimit = 20) {<br>  let plainText = &#39;&#39;;<br>  try {<br>    const parsed = JSON.parse(raw);<br>    if (parsed?.type === &#39;doc&#39;) {<br>      plainText = extractText(parsed);<br>    } else {<br>      plainText = raw;<br>    }<br>  } catch {<br>    plainText = raw || &#39;&#39;;<br>  }<br><br>  const words = plainText.replace(/\s+/g, &#39; &#39;).trim().split(&#39; &#39;).filter(Boolean);<br>  if (words.length &lt;= wordLimit) return { preview: words.join(&#39; &#39;), truncated: false };<br>  return { preview: words.slice(0, wordLimit).join(&#39; &#39;), truncated: true };<br>}</pre><p>The Tiptap bundle is 550kb gzipped — significant. I split it into its own chunk so it only loads when the editor is actually needed, not on the initial page load:</p><pre>// frontend/vite.config.js<br>build: {<br>  rollupOptions: {<br>    output: {<br>      manualChunks: {<br>        &#39;tiptap&#39;: [<br>          &#39;@tiptap/react&#39;,<br>          &#39;@tiptap/starter-kit&#39;,<br>          &#39;@tiptap/extension-underline&#39;,<br>          &#39;@tiptap/extension-strike&#39;,<br>          &#39;@tiptap/extension-link&#39;,<br>          &#39;@tiptap/extension-placeholder&#39;,<br>        ],<br>      },<br>    },<br>  },<br>},</pre><p>Result: main app bundle 55kb, Tiptap loads separately only when needed.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*F_5lvBZrklhb1DxCLSqD6w.png" /><figcaption>The composer with the rich text toolbar visible. Show some formatted text — a heading, bold text, and a bullet list.</figcaption></figure><h3><strong>Part 6: Media Uploads — The Tricky Parts</strong></h3><p>Images are stored as bytea directly in Postgres. This is a deliberate simplicity tradeoff — the correct production answer is S3/object storage — but bytea works fine for a portfolio demo and keeps the infrastructure simple (no S3 bucket, no signed URLs, no separate CDN).</p><p>Two non-obvious problems I had to solve:</p><ol><li><strong>Authenticated Image Fetching</strong></li></ol><p>/api/media/:id requires a Bearer token — you can’t use a plain `&lt;img src=”…”&gt;` because browsers can’t send custom headers on image requests. The solution: fetch the image as a blob and create a local object URL.</p><pre>// frontend/src/components/MediaGallery.jsx<br><br>function MediaThumbnail({ mediaItem, apiUrl, token }) {<br>  const [objectUrl, setObjectUrl] = useState(null);<br><br>  useEffect(() =&gt; {<br>    let cancelled = false;<br>    let createdUrl = null;<br><br>    // Pending items already have a local preview URL — no fetch needed<br>    if (mediaItem.previewUrl) {<br>      setObjectUrl(mediaItem.previewUrl);<br>      return () =&gt; { cancelled = true; };<br>    }<br><br>    fetch(`${apiUrl}/media/${mediaItem.id}`, {<br>      headers: { Authorization: `Bearer ${token}` },<br>    })<br>      .then(res =&gt; res.blob())<br>      .then(blob =&gt; {<br>        if (cancelled) return;<br>        createdUrl = URL.createObjectURL(blob);<br>        setObjectUrl(createdUrl);<br>      });<br><br>    return () =&gt; {<br>      cancelled = true;<br>      // IMPORTANT: object URLs don&#39;t garbage collect automatically<br>      if (createdUrl) URL.revokeObjectURL(createdUrl);<br>    };<br>  }, [mediaItem.id, mediaItem.previewUrl, apiUrl, token]);<br><br>  return objectUrl ? &lt;img src={objectUrl} alt={mediaItem.filename} /&gt; : &lt;div className=&quot;media-thumb-loading&quot; /&gt;;<br>}</pre><p><strong>2.</strong> <strong>Uploading Before the Note Exists</strong></p><p>The upload endpoint is <em>POST /api/notes/:noteId/media</em> — it needs a note ID. When creating a new note, no ID exists yet. The solution: a pending queue with local preview URLs.</p><pre>// In MediaGallery — pending mode (no noteId yet)<br>if (!noteId) {<br>  const previewUrl = URL.createObjectURL(file);<br>  onMediaChange([...(media || []), {<br>    id: `pending-${Date.now()}`,<br>    filename: file.name,<br>    pending: true,<br>    previewUrl,<br>    file,  // Keep the File object for later upload<br>  }]);<br>  return;<br>}</pre><p>When the user clicks “Add note”, the Composer creates the note first, gets the real ID, then flushes the pending uploads:</p><pre>// frontend/src/components/Composer.jsx<br><br>async function handleSubmit(e) {<br>  e.preventDefault();<br>  <br>  // Step 1: Create the note — get a real ID back<br>  const note = await onCreate({ title, content, tags });<br>  <br>  // Step 2: Upload any queued images against the real ID<br>  if (note?.id &amp;&amp; pendingRef.current) {<br>    const uploaded = await pendingRef.current.flush(note.id);<br>    if (uploaded.length &gt; 0) onMediaUploaded?.(note.id, uploaded);<br>  }<br>}</pre><p><strong>3. The Byte Corruption Bug</strong></p><p>During testing, I found that res.send(file.data) was silently JSON-serializing the binary buffer when the data field came back as a Uint8Array -like object rather than a true Node Buffer . The fix:</p><pre>// Explicit coercion — safe even if it&#39;s already a Buffer<br>res.send(Buffer.from(file.data));</pre><p>This is the kind of bug that’s invisible until you byte-diff an uploaded image against what you download back. Testing with real binary files caught it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/340/1*OAW7Yuu5uqJtqBb905i9FQ.png" /><figcaption>A note card in edit mode.</figcaption></figure><h3><strong>Part 7: Auto-Save — Not as Simple as It Sounds</strong></h3><p>Auto-save sounds easy: debounce + save. The reality has several edge cases.</p><pre>// frontend/src/hooks/useAutoSave.js<br><br>export default function useAutoSave(saveFn, deps, { delay = 3000, minContent = null } = {}) {<br>  const [status, setStatus] = useState(&#39;idle&#39;);<br>  const timerRef   = useRef(null);<br>  const saveFnRef  = useRef(saveFn);<br>  const dirtyRef   = useRef(false);<br>  const mountedRef = useRef(true);<br><br>  useEffect(() =&gt; { saveFnRef.current = saveFn; }, [saveFn]);<br>  useEffect(() =&gt; () =&gt; { mountedRef.current = false; }, []);<br><br>  const doSave = useCallback(async () =&gt; {<br>    if (!dirtyRef.current) return;<br>    if (minContent !== null &amp;&amp; !String(minContent).trim()) return;<br>    <br>    dirtyRef.current = false;<br>    setStatus(&#39;saving&#39;);<br>    try {<br>      await saveFnRef.current();<br>      setStatus(&#39;saved&#39;);<br>      setTimeout(() =&gt; { if (mountedRef.current) setStatus(&#39;idle&#39;); }, 2500);<br>    } catch {<br>      setStatus(&#39;error&#39;);<br>    }<br>  }, [minContent]);<br><br>  // Trigger debounced save when deps change<br>  const depsKey = JSON.stringify(deps);<br>  useEffect(() =&gt; {<br>    dirtyRef.current = true;<br>    clearTimeout(timerRef.current);<br>    timerRef.current = setTimeout(doSave, delay);<br>    return () =&gt; clearTimeout(timerRef.current);<br>  }, [depsKey, delay, doSave]);<br><br>  const flushSave = useCallback(async () =&gt; {<br>    clearTimeout(timerRef.current);<br>    await doSave();<br>  }, [doSave]);<br><br>  return { status, flushSave };<br>}</pre><p>The flushSave function is the key — it bypasses the debounce and saves immediately. I call it in three places:</p><ol><li>Window close — beforeunload event</li><li>Manual sign-out — before calling logout()</li><li>Session timeout — before auto-logout</li></ol><p>The Composer has an additional complication: a brand-new note has no ID on first save. It needs to call handleCreate the first time, then PUT on subsequent saves:</p><pre>/ Composer auto-save function<br>const autoSaveFn = useCallback(async () =&gt; {<br>  if (!title.trim()) return;<br><br>  if (!savedNoteId.current) {<br>    // First save — create the note, store the returned ID<br>    const note = await onCreate({ title: title.trim(), content, tags });<br>    if (note?.id) savedNoteId.current = note.id;<br>  } else {<br>    // Subsequent saves — update the existing draft<br>    await fetch(`${apiUrl}/notes/${savedNoteId.current}`, {<br>      method: &#39;PUT&#39;,<br>      headers: { &#39;Content-Type&#39;: &#39;application/json&#39;, Authorization: `Bearer ${token}` },<br>      body: JSON.stringify({ title: title.trim(), content, tags }),<br>    });<br>  }<br>}, [title, content, tags, onCreate, apiUrl, token]);</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xFY2TXMDQr-XR8LfEYautQ.png" /><figcaption>he composer with “✓ Saved” showing in the bottom-left and the “Add note” button to the right.</figcaption></figure><h3>Part 8: Theme Toggle Without the Flash</h3><p>A theme toggle is a CSS variable swap. The hard part is avoiding the flash of wrong theme when the page loads in dark mode — React mounts after HTML is parsed, so without a fix, users always see a white flash before dark mode kicks in.</p><p>The solution: a tiny inline script in index.html that runs before React:</p><pre>&lt;!-- frontend/index.html --&gt;<br>&lt;script&gt;<br>  (function () {<br>    var stored = localStorage.getItem(&#39;notes-app-theme&#39;) || &#39;system&#39;;<br>    var resolved =<br>      stored === &#39;system&#39;<br>        ? (window.matchMedia(&#39;(prefers-color-scheme: dark)&#39;).matches ? &#39;dark&#39; : &#39;light&#39;)<br>        : stored;<br>    document.documentElement.setAttribute(&#39;data-theme&#39;, resolved);<br>  })();<br>&lt;/script&gt;</pre><p>This sets data-theme on synchronously, before any CSS or JS loads. The CSS reads from it:</p><pre>:root {<br>  --paper: #faf7f0;<br>  --ink: #1c1b19;<br>  --accent: #b8893f;<br>  /* ... */<br>}<br><br>[data-theme=&#39;dark&#39;] {<br>  --paper: #1e1e1e;<br>  --ink: #d4d4d4;<br>  --accent: #4fc3f7;<br>  /* ... */<br>}</pre><p>The React context then keeps state in sync, listens for OS preference changes while in “system” mode, and persists the choice to localStorage.</p><h3>Part 9: Handling Render’s Free Tier Sleep</h3><p>Render’s free web services spin down after 15 minutes of inactivity. The first request after sleep can take 30– 60 seconds. To a user who doesn’t know this, it looks like the app is broken.</p><p>The solution: poll /api/health on the login page and show honest feedback.</p><pre>// frontend/src/components/BackendWakeup.jsx<br><br>export default function BackendWakeup({ onReady }) {<br>  const { apiUrl } = useAuth();<br>  const [status, setStatus] = useState(&#39;checking&#39;);<br>  const [elapsed, setElapsed] = useState(0);<br>  const startRef = useRef(Date.now());<br><br>  useEffect(() =&gt; {<br>    const timer = setInterval(() =&gt; {<br>      setElapsed(Math.floor((Date.now() - startRef.current) / 1000));<br>    }, 1000);<br><br>    async function ping() {<br>      try {<br>        const res = await fetch(`${apiUrl}/health`, { signal: AbortSignal.timeout(4000) });<br>        if (res.ok) {<br>          const tookMs = Date.now() - startRef.current;<br>          if (tookMs &lt; 5000) {<br>            onReady();  // Already awake — skip banner entirely<br>          } else {<br>            setStatus(&#39;ready&#39;);<br>            setTimeout(onReady, 1200);<br>          }<br>          return;<br>        }<br>      } catch {}<br>      setStatus(Date.now() - startRef.current &lt; 5000 ? &#39;checking&#39; : &#39;waking&#39;);<br>    }<br><br>    ping();<br>    const poll = setInterval(ping, 2000);<br>    return () =&gt; { clearInterval(timer); clearInterval(poll); };<br>  }, [apiUrl, onReady]);<br><br>  if (status === &#39;checking&#39;) return null;  // Silent — no banner yet<br><br>  const progressPct = Math.min((elapsed / 60) * 100, 95);<br><br>  return (<br>    &lt;div className=&quot;wakeup-banner&quot;&gt;<br>      &lt;div className=&quot;wakeup-top&quot;&gt;<br>        &lt;span className=&quot;wakeup-spinner&quot; /&gt;<br>        &lt;span&gt;Waking up the server… &lt;strong&gt;{elapsed}s&lt;/strong&gt;&lt;/span&gt;<br>        &lt;span className=&quot;wakeup-note&quot;&gt;Free tier sleeps after inactivity — usually 30–60s&lt;/span&gt;<br>      &lt;/div&gt;<br>      &lt;div className=&quot;wakeup-track&quot;&gt;<br>        &lt;div className=&quot;wakeup-fill&quot; style={{ width: `${progressPct}%` }} /&gt;<br>      &lt;/div&gt;<br>    &lt;/div&gt;<br>  );<br>}</pre><p>The form inputs stay disabled while the backend wakes, so a user can’t submit a request that would time out. They enable automatically the moment /api/health responds.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/502/1*fkIy-2-bikHk5GDdYnAcag.png" /><figcaption>The login page while the backend is waking.</figcaption></figure><h3>Part 10: Session Timeout with AutoSave</h3><p>A 1-hour fixed session from login. The hook checks every 30 seconds, shows a warning modal at 60 seconds remaining, saves any open drafts, then logs out.</p><pre>// frontend/src/hooks/useSessionTimeout.js<br><br>export default function useSessionTimeout({ onWarn, onExpire }) {<br>  const [warningSeconds, setWarningSeconds] = useState(null);<br><br>  useEffect(() =&gt; {<br>    const interval = setInterval(() =&gt; {<br>      const loginTime = Number(localStorage.getItem(&#39;login_time&#39;) || 0);<br>      if (!loginTime) return;<br><br>      const remaining = (60 * 60 * 1000) - (Date.now() - loginTime);<br><br>      if (remaining &lt;= 0) {<br>        onExpire?.();<br>      } else if (remaining &lt;= 60 * 1000) {<br>        setWarningSeconds(Math.ceil(remaining / 1000));<br>        onWarn?.();<br>      }<br>    }, 30 * 1000);<br><br>    return () =&gt; clearInterval(interval);<br>  }, []);<br><br>  const extendSession = useCallback(() =&gt; {<br>    localStorage.setItem(&#39;login_time&#39;, String(Date.now()));<br>    setWarningSeconds(null);<br>  }, []);<br><br>  return { warningSeconds, extendSession };<br>}</pre><p>In Dashboard , sign-out always flushes saves first:</p><pre>// Flush both composer draft and any open note edit before logging out<br>const flushAllSaves = useCallback(async () =&gt; {<br>  await Promise.allSettled([<br>    composerSaveRef.current?.flush?.(),<br>    editCardSaveRef.current?.flush?.(),<br>  ]);<br>}, []);<br><br>// Called on manual sign-out<br>&lt;button onClick={async () =&gt; { await flushAllSaves(); logout(); }}&gt;Sign out&lt;/button&gt;</pre><h3>Part 11: One-Click Deploy with Render Blueprint</h3><p>Instead of documenting 20 manual clicks through the Render dashboard, I wrote a render.yaml that deploys everything at once:</p><pre>databases:<br>  - name: notes-db<br>    plan: free<br>    databaseName: notesdb<br>    user: notes_user<br><br>services:<br>  - type: web<br>    name: notes-backend<br>    runtime: node<br>    plan: free<br>    rootDir: backend<br>    buildCommand: npm install<br>    startCommand: npm start<br>    envVars:<br>      - key: DATABASE_URL<br>        fromDatabase:<br>          name: notes-db<br>          property: connectionString  # Wired automatically<br>      - key: JWT_SECRET<br>        generateValue: true           # Render generates this<br>      - key: GOOGLE_CLIENT_ID<br>        sync: false                   # User must provide<br>      - key: CLIENT_ORIGIN<br>        sync: false<br><br>  - type: web<br>    name: notes-frontend<br>    runtime: static<br>    rootDir: frontend<br>    buildCommand: npm install &amp;&amp; npm run build<br>    staticPublishPath: dist<br>    envVars:<br>      - key: VITE_API_URL<br>        sync: false<br>      - key: VITE_GOOGLE_CLIENT_ID<br>        sync: false<br>    routes:<br>      - type: rewrite<br>        source: /*<br>        destination: /index.html     # Required for React Router</pre><p>The `rewrite` rule at the bottom is easy to forget and causes confusing 404s — without it, refreshing on any route other than `/` returns a 404 from the static host because the file doesn’t exist on disk.</p><p>`DATABASE_URL` and `JWT_SECRET` wire themselves automatically. The only values you fill in manually are the ones that genuinely can’t be generated: Google Client ID, the two URLs that only exist after first deploy.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xQDJlO15kJ7Lz4vUQ9U6Ew.png" /><figcaption>The Render dashboard showing all three services (notes-db, notesbackend, notes-frontend) all showing green “Live” status.</figcaption></figure><p><strong>What I’d Do Differently</strong></p><p><strong>Move media to object storage sooner. </strong>bytea -inPostgres works but it bloats the database and doesn’t scale. S3 or Cloudflare R2 (which has a generous free tier) is the right answer for anything real.</p><p><strong>Add JWT revocation.</strong> Logging out just discards the local token, but the 7-day JWT is still technically valid server-side until expiry. A revoked_tokens table checked in requireAuth would close this gap.</p><p><strong>Add structured logging</strong>. console.error is fine locally but makes production debugging harder. Pino or Winston with JSON output is the right answer before traffic gets meaningful.</p><p><strong>Test against real Postgres from day one</strong>. I used PGlite (a WASM build of actual Postgres) for most testing, which caught real bugs — including a bytea serialization issue that would have silently corrupted downloaded images. But testing against the actual Render-hosted database would have caught the timing issues faster.</p><h3>Final Thoughts</h3><p>The thing I’m most proud of in this project isn’t any individual feature — it’s that every decision has a reason behind it. The search_vector generated column instead of application-side index maintenance. The magic-byte file validation instead of trusting Content-Type. The flushSave() ref pattern so Dashboard can save drafts without prop-drilling through every component. The anti-flash inline script in index.html .</p><p>None of these are clever hacks. They’re straightforward solutions to real problems, and being able to explain why each one exists is exactly what separates a working demo from production-ready code.</p><p>If you want to explore the code, it’s all at <a href="https://github.com/Rememberful/Secured-notetaking.git">github.com/Rememberful/secured-messaging</a></p><p>The live demo is at</p><p><a href="https://notes-frontend-j8qo.onrender.com/login">notes-frontend-j8qo.onrender.com</a></p><p>— give it 30 seconds to wake up if it’s sleeping.</p><p><strong>Contact Me</strong><br>📧 <strong>Email:</strong> adii.utsav@gmail.com<br>🔗 <strong>LinkedIn:</strong> <a href="https://www.linkedin.com/in/aditya-kumar-3241b6286/">https://www.linkedin.com/in/aditya-kumar-3241b6286/</a><br>💻 <strong>GitHub:</strong> <a href="https://github.com/Rememberful">https://github.com/Rememberful</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e4a1fd147129" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Host a Website on Amazon S3: A Beginner’s Guide to Static Website Hosting]]></title>
            <link>https://medium.com/@adii.utsav/host-a-website-on-amazon-s3-a-beginners-guide-to-static-website-hosting-5f213a894069?source=rss-f1d05be749b2------2</link>
            <guid isPermaLink="false">https://medium.com/p/5f213a894069</guid>
            <category><![CDATA[s3-bucket]]></category>
            <category><![CDATA[deployment]]></category>
            <category><![CDATA[s3]]></category>
            <category><![CDATA[website]]></category>
            <category><![CDATA[aws]]></category>
            <dc:creator><![CDATA[Aditya Kumar]]></dc:creator>
            <pubDate>Thu, 09 Jul 2026 09:44:57 GMT</pubDate>
            <atom:updated>2026-07-09T09:44:57.276Z</atom:updated>
            <content:encoded><![CDATA[<p><em>By Aditya Kumar</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1DblbfB_wrMr_k-P7zbydg.png" /><figcaption>Generated using Gemini</figcaption></figure><p>If you’ve ever wanted to put a simple website online without paying for a server, Amazon S3 (Simple Storage Service) is one of the easiest and cheapest ways to do it. In this project, we’ll walk through hosting a static website on S3, securing it with a bucket policy, sharing content temporarily with presigned URLs, and updating the site once it’s live.</p><p>By the end of this article, you’ll understand:</p><ol><li>How to create and configure an S3 bucket</li><li>How to set up static website hosting</li><li>How to manage public access to your files</li><li>How to generate a presigned URL for temporary, time-limited access</li><li>How to enable versioning</li><li>How to secure your bucket with a bucket policy</li><li>How to update your website after it’s already deployed</li></ol><p>Let’s dive in.</p><p>Open the S3 bucket section: following screen will appear</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*xxLB1r8pGHDxEvYXP7GI1Q.png" /></figure><p>Click on the “orange” button: following page will open, fill it up</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*NWNl5u98nAK_1kbpLKwJag.png" /></figure><p>Should appear like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*gK6I9AWEiM8i5Npoa2tuaA.png" /></figure><p>Scroll down and allow it to be accessed by the public:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*YkoO4YZSloLD3T8SYSJVGw.png" /></figure><p>Now, enable the bucket versioning:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*6U2i562Ejvq3B7w2psfaAQ.png" /></figure><p>Leave rest of the options as default, and then click on the Create bucket button at the bottom of the page, following confirmation will occur:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*ttlh1wjhxNZntz3OEwS-wQ.png" /></figure><p>Now, click on the bucket: following screen will appear</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*Jm1GYIEGGgrmHGOGlNsEIw.png" /></figure><p>Click on the orange “upload” button: upload the index.html file and the other files</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*KCK0l5Q53nSKzuhXkRVj1Q.png" /></figure><p>Following confirmation will occur:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*UVNvzz5rMP_tOYg_jj7Wuw.png" /></figure><p>We will be able to see the following objects inside the bucket:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*mPEaa5Vc2vkzjCyR3ZMf9A.png" /></figure><p>Go to the bucket -&gt; properties -&gt; scroll down to the “Static Website hosting”:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*FS0cwkNJ3FmPaK6_VWynuw.png" /></figure><p>Click on the “Edit” button: following screen will appear</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*l6VlA1GgUT0ILrgcfbLzaw.png" /></figure><p>Click on the “enable” radio button: following options will occur</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*OauPJ9DCBFcJLtGhLTaNLQ.png" /></figure><p>Fill it accurately: then scroll down to click on the “save changes” button</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*R-IqD6XEZJOw2NCKM-TctQ.png" /></figure><p>We will be able to observe a link at the section of “static website” like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*HyFdFRaUsRLzE1tksPn2Rw.png" /></figure><p>Copy &amp; paste the link in the new tab: following error will occur</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*Axb-RgFBMDihgVcgHZ_9xw.png" /></figure><p>So, how to deal with this error?</p><p>Select the objects in the bucket, and click on the “actions” button: following menu will appear</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*0x7qGRJBAYO0CxmnZw_TDw.png" /></figure><p>Click on the “Make public using ACL” option: following screen will appear</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*NRXt-Jk70XFUl-scZ1WXrQ.png" /></figure><p>Then click on the make public button: following confirmation will occur</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*d-tqIlub52gaO4gv56Cuhg.png" /></figure><p>Now, just the tab, which had the error: the following page will now occur</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*SPk26vAsfDLm0yUejmUCBw.png" /></figure><p><strong>Contact Me</strong><br>📧 <strong>Email:</strong> adii.utsav@gmail.com<br>🔗 <strong>LinkedIn:</strong> <a href="https://www.linkedin.com/in/aditya-kumar-3241b6286/">https://www.linkedin.com/in/aditya-kumar-3241b6286/</a><br>💻 <strong>GitHub:</strong> <a href="https://github.com/Rememberful">https://github.com/Rememberful</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5f213a894069" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>