<?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 Kishore K on Medium]]></title>
        <description><![CDATA[Stories by Kishore K on Medium]]></description>
        <link>https://medium.com/@kishoregillu?source=rss-31d8ce6977d0------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*rBYfJB5tYP3KFGaAEizELQ.png</url>
            <title>Stories by Kishore K on Medium</title>
            <link>https://medium.com/@kishoregillu?source=rss-31d8ce6977d0------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 21 Nov 2026 12:45:30 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@kishoregillu/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[How to Persist React Table Filters Using localStorage: A Practical React Guide]]></title>
            <link>https://medium.com/@kishoregillu/how-to-persist-react-table-filters-using-localstorage-a-practical-react-guide-2b25667bad27?source=rss-31d8ce6977d0------2</link>
            <guid isPermaLink="false">https://medium.com/p/2b25667bad27</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[frontend]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[localstorage]]></category>
            <dc:creator><![CDATA[Kishore K]]></dc:creator>
            <pubDate>Wed, 01 Jul 2026 13:24:13 GMT</pubDate>
            <atom:updated>2026-07-01T13:24:13.835Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ljC8uUn_KkqVE3_J_TatZg.png" /><figcaption>Persisting React table filters using localStorage</figcaption></figure><h3>1. Introduction</h3><p>Tables are a core part of many React applications, whether you’re building an admin dashboard, a CRM, an e-commerce platform, or a reporting system. Users often rely on filters such as search text, status, category, or date range to quickly find the information they need.</p><p>However, there’s a common usability issue that many developers overlook. When a user refreshes the page or accidentally closes and reopens the browser, all the applied filters are lost because React state is reset. The user has to manually reapply every filter, which can be frustrating — especially when working with large datasets.</p><p>A simple and effective solution is to persist the filter state using the browser’s localStorage. By saving the user&#39;s filter selections and restoring them when the application loads, you can create a smoother and more user-friendly experience with minimal code changes.</p><p>In this guide, we’ll build a React table that remembers its filters even after a page refresh. You’ll learn how to save filter values to localStorage, restore them when the component loads, and implement this pattern in a clean, reusable way that can be applied to many React applications.</p><h3><strong>2. The Problem</strong></h3><p>Imagine you’re working on an admin dashboard that displays hundreds of records in a table. To find the information you need, you apply multiple filters — for example:</p><p>* Search for ”John”<br>* Set Status = Active<br>* Choose Department = Engineering</p><p>The table now displays only the records you’re interested in. Everything works as expected.</p><p>Now suppose you accidentally refresh the page (or press F5). As soon as the page reloads, all the applied filters disappear, and the table returns to its default state. You have to manually select each filter again before you can continue working.</p><p>This happens because React stores component state in memory. When the browser refreshes the page, the component is recreated, and its state is initialized with the default values.</p><p>Before Refresh<em><br> — — — — — — — — — — — -<br>Search : John<br>Status : Active<br>Department : Engineering</em></p><p><em>User presses F5</em></p><p>After Refresh<em><br> — — — — — — — — — — — -<br>Search : “”<br>Status : All<br>Department : All</em></p><p>While this behavior is expected, it doesn’t provide the best user experience. In applications where users frequently work with large datasets, losing filter selections after every refresh can become frustrating and reduce productivity.</p><p>To solve this problem, we need a way to preserve the filter state even when the page reloads. Fortunately, the browser provides a simple solution: <strong>localStorage</strong>. By saving the current filter values whenever they change and restoring them when the component loads, we can ensure that users return to the same filtered view they were working with before the refresh.</p><h3>3. Understanding localStorage</h3><p>localStorage is a built-in Web Storage API provided by modern browsers that allows you to store data as key-value pairs directly in the user&#39;s browser. Unlike React state, the data stored in localStorage is not cleared when the page is refreshed or the browser is restarted.</p><p>This makes it an excellent choice for storing small pieces of information such as:</p><ul><li>User preferences</li><li>Theme settings (Light/Dark mode)</li><li>Language selection</li><li>Recently viewed items</li><li>Table filter values</li><li>Pagination settings</li></ul><p>One important thing to remember is that localStorage stores <strong>only strings</strong>. If you want to store JavaScript objects or arrays, you must convert them into a JSON string before saving them. Likewise, when retrieving the data, you&#39;ll need to parse the JSON string back into a JavaScript object.</p><p>For example:</p><pre>// Save filter values<br>const filters = {<br>  search: &quot;John&quot;,<br>  status: &quot;Active&quot;,<br>  department: &quot;Engineering&quot;,<br>};</pre><pre>localStorage.setItem(&quot;tableFilters&quot;, JSON.stringify(filters));</pre><pre>// Retrieve filter values<br>const savedFilters = JSON.parse(localStorage.getItem(&quot;tableFilters&quot;));</pre><pre>console.log(savedFilters);</pre><p>In the example above, the filter object is converted into a JSON string using JSON.stringify() before being stored. When the data is read back, JSON.parse() converts it into a JavaScript object that can be used to initialize the React component.</p><h3>Why use localStorage for table filters?</h3><p>Using localStorage offers several advantages:</p><ul><li>It improves the user experience by remembering filter selections across page refreshes.</li><li>It requires no backend or database changes.</li><li>It’s supported by all modern browsers.</li><li>It’s simple to implement with just a few lines of code.</li><li>It’s ideal for storing lightweight UI state, such as filter values and user preferences.</li></ul><p>However, localStorage is best suited for small amounts of non-sensitive data. Since the data is stored in the user&#39;s browser and is accessible through JavaScript, you should avoid storing sensitive information such as passwords, authentication tokens, or personal data.</p><p><em>Visual Diagram</em></p><p>User Changes Filter<br> │<br> ▼<br>React State Updates<br> │<br> ▼<br>Save to localStorage<br> │<br> ▼<br>Page Refresh<br> │<br> ▼<br>Read from localStorage<br> │<br> ▼<br>Restore React State<br> │<br> ▼<br>Table Shows Previous Filters</p><h3>4. Implementing Filter Persistence in React</h3><p>Now that we understand how localStorage works, let&#39;s implement filter persistence in a React application.</p><p>Our goal is simple:</p><ol><li>Store the current filter values whenever they change.</li><li>Restore those values when the component loads.</li><li>Display the table using the restored filters.</li></ol><p>Let’s implement this one step at a time.</p><h3>Step 1: Create the Filter State</h3><p>First, create a state object to store all the filter values.</p><pre>const [filters, setFilters] = useState({<br>  search: &quot;&quot;,<br>  status: &quot;All&quot;,<br>  department: &quot;All&quot;,<br>});</pre><p>Instead of creating multiple state variables, grouping related filters into a single object makes the code easier to manage and update.</p><h3>Step 2: Restore Saved Filters</h3><p>When the component loads for the first time, check whether filter values already exist in localStorage.</p><pre>useEffect(() =&gt; {<br>  const savedFilters = localStorage.getItem(&quot;tableFilters&quot;);</pre><pre>  if (savedFilters) {<br>    setFilters(JSON.parse(savedFilters));<br>  }<br>}, []);</pre><p>Here’s what’s happening:</p><ul><li>localStorage.getItem() retrieves the previously saved filters.</li><li>If filter data exists, it is converted back into a JavaScript object using JSON.parse().</li><li>The restored object is then assigned to the React state using setFilters().</li></ul><p>As a result, the user sees the same filter selections they were using before refreshing the page.</p><h3>Step 3: Save Filters Whenever They Change</h3><p>Next, save the latest filter values every time the user changes a filter.</p><pre>useEffect(() =&gt; {<br>  localStorage.setItem(<br>    &quot;tableFilters&quot;,<br>    JSON.stringify(filters)<br>  );<br>}, [filters]);</pre><p>This useEffect runs whenever the filters state changes.</p><p>For example:</p><ul><li>User types in the search box.</li><li>User changes the status filter.</li><li>User selects another department.</li></ul><p>Each update automatically saves the latest filter values to localStorage, ensuring the most recent state is always available after a page refresh.</p><p>At this point, we’ve successfully connected React state with localStorage. The remaining step is to update the filter state whenever the user interacts with the UI so that both the application and localStorage stay synchronized.</p><h3>Step 4: Connect the Filter Inputs</h3><p>Now that we’ve implemented the logic for saving and restoring filter values, the next step is to connect the user interface to the filters state.</p><p>Whenever a user updates a filter, we need to:</p><ol><li>Update the React state.</li><li>Automatically save the latest filter values to localStorage (handled by our useEffect).</li></ol><p>For example, let’s create a search input.</p><pre>&lt;input<br>  type=&quot;text&quot;<br>  placeholder=&quot;Search...&quot;<br>  value={filters.search}<br>  onChange={(e) =&gt;<br>    setFilters({<br>      ...filters,<br>      search: e.target.value,<br>    })<br>  }<br>/&gt;</pre><p>Notice that the input’s value is bound to filters.search. This ensures that:</p><ul><li>The UI always reflects the current React state.</li><li>Restored values from localStorage automatically appear in the input after a page refresh.</li></ul><p>Similarly, you can connect a status dropdown.</p><pre>&lt;select<br>  value={filters.status}<br>  onChange={(e) =&gt;<br>    setFilters({<br>      ...filters,<br>      status: e.target.value,<br>    })<br>  }<br>&gt;<br>  &lt;option value=&quot;All&quot;&gt;All&lt;/option&gt;<br>  &lt;option value=&quot;Active&quot;&gt;Active&lt;/option&gt;<br>  &lt;option value=&quot;Inactive&quot;&gt;Inactive&lt;/option&gt;<br>&lt;/select&gt;</pre><p>Every time the user changes a filter:</p><ul><li>The filters state is updated.</li><li>The useEffect responsible for saving filters is triggered.</li><li>The latest filter values are written to localStorage.</li></ul><p>This means you don’t need to manually call localStorage.setItem() inside every event handler. Keeping the save logic in a dedicated useEffect results in cleaner, more maintainable code.</p><p>By following this pattern, all filter controls remain synchronized with the React state, making it easy to add additional filters such as date ranges, categories, or priority levels without changing the persistence logic.</p><h3>Step 5: Apply the Filters to the Table</h3><p>At this point, the filter values are successfully stored in React state and persisted in localStorage. The final step is to use those values to display only the matching records in the table.</p><p>Suppose we have the following employee data:</p><pre>const employees = [<br>  {<br>    id: 1,<br>    name: &quot;John Smith&quot;,<br>    status: &quot;Active&quot;,<br>    department: &quot;Engineering&quot;,<br>  },<br>  {<br>    id: 2,<br>    name: &quot;Alice Johnson&quot;,<br>    status: &quot;Inactive&quot;,<br>    department: &quot;HR&quot;,<br>  },<br>  {<br>    id: 3,<br>    name: &quot;John Doe&quot;,<br>    status: &quot;Active&quot;,<br>    department: &quot;Engineering&quot;,<br>  },<br>];</pre><p>We can filter the data based on the current filter state.</p><pre>const filteredEmployees = employees.filter((employee) =&gt; {<br>  const searchMatch =<br>    employee.name<br>      .toLowerCase()<br>      .includes(filters.search.toLowerCase());</pre><pre>  const statusMatch =<br>    filters.status === &quot;All&quot; ||<br>    employee.status === filters.status;</pre><pre>  const departmentMatch =<br>    filters.department === &quot;All&quot; ||<br>    employee.department === filters.department;</pre><pre>  return (<br>    searchMatch &amp;&amp;<br>    statusMatch &amp;&amp;<br>    departmentMatch<br>  );<br>});</pre><p>Now render the filtered data instead of the original array.</p><pre>&lt;tbody&gt;<br>  {filteredEmployees.map((employee) =&gt; (<br>    &lt;tr key={employee.id}&gt;<br>      &lt;td&gt;{employee.name}&lt;/td&gt;<br>      &lt;td&gt;{employee.status}&lt;/td&gt;<br>      &lt;td&gt;{employee.department}&lt;/td&gt;<br>    &lt;/tr&gt;<br>  ))}<br>&lt;/tbody&gt;</pre><h3>How it works</h3><p>Let’s walk through a typical user interaction:</p><ol><li>The user enters <strong>“John”</strong> in the search box.</li><li>The user selects <strong>Status = Active</strong>.</li><li>React updates the filters state.</li><li>The updated filter values are automatically saved to localStorage.</li><li>The table immediately displays only the matching records.</li><li>The user refreshes the page.</li><li>The saved filters are restored from localStorage.</li><li>The table is filtered automatically, without requiring the user to reapply the filters.</li></ol><p>This creates a seamless experience where users can continue working from exactly where they left off, even after refreshing the browser.</p><h3>5. Handling Edge Cases and Best Practices</h3><p>The implementation we’ve built works well for most applications. However, there are a few edge cases and best practices you should consider before using this approach in a production environment.</p><h3>i). Handle Missing or Invalid Data</h3><p>The first time a user visits your application, there won’t be any saved filter values in localStorage. Additionally, stored data could become corrupted or manually modified.</p><p>Instead of assuming the data is always valid, safely parse it using a try...catch block.</p><pre>useEffect(() =&gt; {<br>  try {<br>    const savedFilters = localStorage.getItem(&quot;tableFilters&quot;);</pre><pre>    if (savedFilters) {<br>      setFilters(JSON.parse(savedFilters));<br>    }<br>  } catch (error) {<br>    console.error(&quot;Invalid filter data found in localStorage&quot;);<br>    localStorage.removeItem(&quot;tableFilters&quot;);<br>  }<br>}, []);</pre><p>This prevents your application from crashing if invalid JSON is encountered.</p><h3>ii). Use Meaningful Storage Keys</h3><p>Avoid generic keys like:</p><pre>filters<br>data<br>table</pre><p>Instead, use descriptive names that clearly identify the stored data.</p><pre>employeeTableFilters<br>jiraTableFilters<br>productTableFilters<br>reportFilters</pre><p>This reduces the chance of collisions when your application stores multiple items in localStorage.</p><h3>iii). Store Only What You Need</h3><p>Only save the filter values.</p><p>✅ Good</p><pre>{<br>  search: &quot;John&quot;,<br>  status: &quot;Active&quot;,<br>  department: &quot;Engineering&quot;<br>}</pre><p>❌ Avoid</p><pre>{<br>  filters: {...},<br>  tableData: [...5000 records...]<br>}</pre><p>Large datasets consume unnecessary storage space and can impact performance. It’s better to fetch fresh data from the server and apply the saved filters.</p><h3>iv). Provide a Way to Clear Filters</h3><p>Users should be able to reset both the UI and the stored filter values.</p><pre>const clearFilters = () =&gt; {<br>  const defaultFilters = {<br>    search: &quot;&quot;,<br>    status: &quot;All&quot;,<br>    department: &quot;All&quot;,<br>  };</pre><pre>  setFilters(defaultFilters);<br>  localStorage.removeItem(&quot;tableFilters&quot;);<br>};</pre><p>This ensures that users can easily start with a clean state.</p><h3>v). Keep Persistence Logic Separate</h3><p>A common mistake is calling localStorage.setItem() inside every onChange handler.</p><p>Instead of this:</p><pre>onChange={() =&gt; {<br>   setFilters(...);<br>   localStorage.setItem(...);<br>}}</pre><p>Use a dedicated useEffect to handle persistence whenever the filter state changes.</p><p>This keeps your event handlers focused on updating state and makes your code easier to maintain.</p><h3>vi). Avoid Storing Sensitive Information</h3><p>Remember that localStorage is accessible from the browser&#39;s developer tools.</p><p>Never store:</p><ul><li>Passwords</li><li>Authentication tokens</li><li>Personal information</li><li>Payment details</li></ul><p>localStorage is best suited for non-sensitive UI preferences such as filter values, themes, pagination settings, and language preferences.</p><h3>vii). Think About Expiration (Optional)</h3><p>In some applications, you may not want filter values to persist indefinitely.</p><p>For example:</p><ul><li>A reporting dashboard might remember filters for one day.</li><li>An analytics application might clear filters after logout.</li><li>An admin panel might reset filters when a new session begins.</li></ul><p>You can implement this by storing a timestamp along with the filter values and removing them after a specified duration.</p><p>By following these best practices, your implementation becomes more robust, maintainable, and suitable for real-world React applications. While persisting filter values may seem like a small enhancement, it significantly improves the overall user experience by allowing users to continue where they left off.</p><h3>7. Conclusion</h3><p>Persisting table filters may seem like a small enhancement, but it can make a significant difference in the overall user experience. By storing filter values in localStorage, users can refresh the page, reopen the browser, or return to the application later without losing the context of their work.</p><p>In this guide, we covered how to:</p><ul><li>Create a centralized filter state using React Hooks.</li><li>Save filter values to localStorage.</li><li>Restore saved filters when the component loads.</li><li>Connect filter inputs to React state.</li><li>Apply filters to table data.</li><li>Handle common edge cases and follow production-ready best practices.</li></ul><p>Although our example focused on table filters, the same approach can be used for many other UI preferences, including pagination, sorting, selected tabs, dashboard layouts, theme preferences, and language settings.</p><p>Remember that localStorage is best suited for storing lightweight, non-sensitive data. For larger datasets or sensitive information, consider more appropriate storage solutions or server-side persistence.</p><p>I hope this guide helps you build React applications that provide a smoother and more user-friendly experience. If you’ve implemented a different approach to state persistence or have suggestions for improving this pattern, feel free to share your thoughts. Learning from different implementation strategies is one of the best ways to grow as a React developer.</p><p><strong>Happy coding!</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2b25667bad27" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>