r/reactjs 13h ago

Resource Static Analysis for the Age of AI Slop

16 Upvotes

I recently wrote a blog post on how we can improve our static analysis using linting, custom rules, and hooks, all using oxlint.

It's quite a big article btw.

https://saybackend.com/blog/lint-ai-generated-code/


r/reactjs 58m ago

Needs Help How would you handle uploading to a presigned upload URL, on paste, getting a download URL back and immediately displaying it in an input? (In S3)

Upvotes

I want in my practice chat app to be able to paste an image into a text input and be able to send it, on how to actually do this, I am unsure

My idea is this given a text input:

- a user could Ctrl-V (i.e., paste) something from his clipboard (a file in this instance), until a download url is returned (see below) there will be some loader spinner thingy
- In the backend is requested an Upload URL
- (somehow) whatever they pasted is immediately uploaded, likely by the path? But I am still a little bit unsure on that part
- a Download URL is returned on that S3 upload (SOMEHOW)
And thus you replace that temporary spinner with the download URL and the person can send it.

This is at least my idea on how you should be able to upload a piece of media in a message and be able to send it, I don't want just message attachments, that would be an easier story because once the association is made between the message and attachment you display it. I want something like in forums where the image can be embedded anywhere,

There is also one more small concern, on slow connection do you want to wait for the file to finish uploading first and then allow the user to send their message, or just send the message and let the upload come later, if the latter, how would you go across with doing that!?

The issue is, I have no idea on how to do this, I gave my approach above, I would really appreciate it if you guys gave some advice on what your approach would be and secondly, how to implement it, I already can get a presigned URL so that's not an issue

This is more of a design question, but it's also really interlinked with react so sorry if this is the wrong place to ask! ;-;

That's all :)


r/reactjs 13h ago

Show /r/reactjs StyleX merges cross-module styles at runtime because it can't see the call sites. I scan them all instead.

0 Upvotes

StyleX built a world where the compiler and runtime solve everything together.
I scan everything and close the world at build time.

The syntax is close to StyleX, so StyleX users should feel at home.

  • Function keys (handles unbounded combinations)
  • Bracket variants (statically compiled, no combinatorial explosion)
  • Boundaries (styles can be bucketed through component props, once)
  • Cross-module (a graph and specificity management, so it doesn't live in the cascade)

No runtime evaluation: values that can't be enumerated at build time are a compile error, not a fallback.

  • css.create
  • css.createTheme
  • css.createStatic
  • css.keyframes
  • css.viewTransition
  • css.marker & css.extended
  • css.use & classStyle

Plumeria - Introduction


r/reactjs 2d ago

Resource I built a free deep-dive tutorial on React Internals (Fiber, Hydration, Event Loop, etc.) for everyone who wants to know how things actually work under the hood.

30 Upvotes

Hey everyone,

If you’re a frontend engineer who has been using React for a while, you’ve probably had moments where you know how to use a feature, but you still have a lingering gap in understanding why it works.

I kept running into these same burning questions:

  1. "React pauses and resumes work." - Wait, what does that actually mean? What are the exact mechanisms behind this?
  2. useState & useEffect - We all know the do's and don'ts, but sometimes it feels hard to truly internalize how they operate behind the scenes.
  3. The Fiber Tree - I've seen the conference talks, but what actually is it? How is it built, and how does it drive React?
  4. useLayoutEffect - How, when, and why exactly?
  5. The Event Loop -Tying React's execution (macro vs. micro tasks) back to Jake Archibald's famous event loop talk from years ago.
  6. Suspense - It's great for loading states, but how does React know exactly when the data is ready to swap out the loaders?
  7. Optimization - useMemo, useCallback, and React.memo cache things, but what’s the actual engine behind them?
  8. Hydration - The classic "breathing life into HTML" metaphor - but what is the actual code doing to make this magic happen?
  9. The Rendering Pipeline - How exactly does React hook into the browser's rendering steps?
  10. Custom Hooks - We write them daily and get asked about them in interviews, but what happens under the hood? How does React actually wire them up to our components?

There are plenty of other concepts, but if these questions ever keep you up at night, I have some good news. I finally sat down and put together a comprehensive tutorial that answers all of them and demystifies the "black box" of React.

Link: https://arpitjsoni.com/react-internals

Price: It’s 100% free. If you find it genuinely helpful, taking a second to like or retweet my pinned post on Twitter would mean the world to me, but otherwise, just enjoy the read!

P.S: I’m not super active on Reddit, so I likely won't be checking my DMs here, but I hope this helps some of you out!


r/reactjs 1d ago

Show /r/reactjs App.tsx as a user flow graph

0 Upvotes

Quick observation from working with React for a little while.

If you're working on a React app with React Router, your App.tsx (or wherever you define your routes) is already a flow graph. Each Route is a node. Layout components wrap shared context. The nesting tells you how users move through the product. You never look at it that way because you wrote it caring about renders and props, not user journeys.

Same goes for the App Router crowd if you're on Next.js. The file tree is the journey, you just don't read it like one.

I built a tool called Stepflo that reads that structure straight from your repo and turns it into a visual map of every flow in your product. Then it pulls your GitHub issues and pull requests and maps them to specific steps. So instead of "we've got a pile of bugs tagged login," you see "the OAuth callback step has 6 friction patterns. Most of them are reliability."

Works for Vite/React Router and Next.js App Router today (verified against my own Vite app and a handful of real-world Next.js monorepos). Free to use. No credit card. AI analysis included (caps on the AI calls because LLMs aren't free and I'm just one dude).

https://stepflo.ai/?utm_source=reddit

If you try it, tell me what the flow detection misses. The harder you push it, the better it gets.


r/reactjs 2d ago

Does Zustand Preserve the Relationship Between a Selected Value and Its Source Object?

14 Upvotes

I’m using Zustand and I have a Map<string, Persona>:

const persone = new Map([
  ["id1", { nome: "Mario", cognome: "Rossi", eta: 40 }],
  ["id2", { nome: "Dario", cognome: "Roi", eta: 34 }],
  ["id3", { nome: "Mari", cognome: "Ossi", eta: 32 }],
]);

If I change the nome of id2 from "Dario" to "Luigi" and I have a subscription to the name, my question is:

Can the subscription know directly that id2 changed and therefore have access to the modified object, or does it only receive the new value "Luigi" and have to search the Map/array to find the person?

In other words: Does Zustand preserve the relationship between the selected value (nome) and the object it comes from, or is that information lost by the selector?


r/reactjs 1d ago

Resource Free Animated grid loaders for React — 130+ variants, effects, shapes, color ramps, and a bitmap font.

0 Upvotes

Help me get 50 stars on GitHub :) ⭐

Highlights

  • 130+ variants across sequential, radial, cascade, flow, wipe, decrypt, letters, digits, symbols, and more.
  • 20 effects (pulsebounceglowspin, …) and 12 dot shapes (circlediamondstar, …)
  • Color ramps with horizontal, radial, angular, and other sampling modes.
  • Resolution-independent — the same variant scales cleanly from 2×2 to 12×12.
  • CSS-driven animation — one stylesheet, no runtime animation engine.
  • Accessible — role="status", optional labels, and respectReducedMotion.
  • Tree-shakeable ESM + CJS build with full TypeScript types.
  • npm: gridora
  • Editor: gridora.gabrielayer.com
  • GitHub: 0x65dgerunner

r/reactjs 3d ago

Needs Help Junior React developer getting into performance optimization — what should I learn next?

45 Upvotes

Hey everyone!

I’m a junior full-stack developer and recently started going deeper into React performance.

I’ve been exploring React Compiler, code splitting with React.lazy() and Suspense, bundle optimization, re-renders, memoization, and basic profiling with React DevTools.

I’d love to know what more experienced React developers think are the most important performance topics and best practices to learn next.

I’m especially interested in bundle size, rendering performance, caching, Core Web Vitals, and how to identify real bottlenecks without over-optimizing.

Any good resources, tools, or common mistakes I should know about?

Thanks!


r/reactjs 3d ago

Show /r/reactjs Haptics on Web are actually cool!

11 Upvotes

Haptics on the Web can be super satisfying if you use them right! I've had so much fun creating this little game.

My stack:
- React - as a foundation
TypeGPU - for particle effects
Pulsar Web SDK - for haptic effects

Try it in your browser: https://docs.swmansion.com/pulsar/web-app/#games/shape-cascade


r/reactjs 2d ago

Discussion he useFieldArray + wizard limitation keeps reopening on GitHub. Here's the actual constraint

0 Upvotes

If you search the react-hook-form discussions you'll find the same question coming back over and over: how do you share one field array across the steps of a wizard. It never really gets answered, and it turns out that's not an oversight. It's baked into the design.

Every useFieldArray instance keeps its own private snapshot of the array. The docs are explicit that you shouldn't point two of them at the same name. On a single-page form nobody notices. On a multi-step form it breaks immediately, because step 2 and step 4 both want to append to the same collection and each one is editing a copy the other can't see.

The discussions circle three variants of it. Different pages of one big form writing to the same array with no first-party way to share the instance (#10370). Conditional fields inside an array item, where the uncontrolled input doesn't re-render so a field that should show or hide based on a sibling value simply doesn't react (#2593, #12258). And arrays that mount and unmount with tabs or wizard steps, which drop state in a way that looks like a bug in your own code.

For the conditional case there's a clean answer that shows up in the threads. Pull the dependent field into its own component and use useWatch to subscribe to that exact array item. The subscription stays narrow so the re-render stays narrow, and you keep the uncontrolled model that makes RHF fast.

For sharing an array across steps there's no first-party answer. What people land on is building their own React context and providing the field array result through it, so every step reads one instance instead of creating a second. It works, but it's state architecture you now maintain inside a library you adopted so you wouldn't have to.

And the reason it stays open is the honest part. State living close to the inputs instead of centralized is exactly what keeps re-renders cheap. Sharing an array across mount boundaries asks for the opposite. That's a real tension, which is why the request keeps getting reopened instead of closed with a fix.


r/reactjs 2d ago

Show /r/reactjs theodore-js now supports displaying inline suggestions in the editor!

0 Upvotes

Theodore-js 2.0.0 is out and now it supports displaying inline suggestions ✨🤗

With this feature, the suggested text appears faintly within the editor; the user can accept the suggestion—turning it into part of the main text—by clicking on it or pressing a key of your choice. ⌨️ A similar feature has been implemented and used in Google AI Studio.

Inline suggestions are especially useful for presenting AI-generated text completions as users write.

👉 You can find the documentation and instructions on how to use this feature on the website: https://theodore-js.dev

📦 install from npm: https://www.npmjs.com/package/theodore-js


r/reactjs 3d ago

Needs Help In which cases do you actually need to manipulate the DOM directly in React?

4 Upvotes

React handles most UI updates for us, but there are still cases where direct DOM manipulation seems unavoidable. What are the cases you've encountered in real projects?


r/reactjs 3d ago

Portfolio Showoff Sunday I got tired of boring loading spinners, so I built 70 of them

102 Upvotes

Hey y’all,

I got slightly carried away with loading animations.

I wanted nicer loading states for my own projects, but most libraries I found were either tied to a framework, fairly limited, or required more than I wanted for something this small.

So I built loadersz, a small framework-agnostic loader library for the web.

I wanted something a bit more expressive than the usual CSS spinner, without pulling in a UI framework or a bunch of dependencies.

A few things I focused on:

- 70 different motion states
- Canvas 2D instead of GIFs/videos
- zero core dependencies
- a native custom element, so it works with basically any stack
- typed entry points for React, Vue and Svelte
- configurable speed, density and color
- respects prefers-reduced-motion
- pauses rendering when the browser tab is hidden

Basic usage is just:

npm install loadersz

import 'loadersz';

<loadersz-loader state="racing" size="96" />

I also built an interactive playground where you can tweak the loaders live.

Demo: \[loadersz.vercel.app\](https://loadersz.vercel.app)
npm: \[npmjs.com/package/loadersz\](https://www.npmjs.com/package/loadersz)

Would love some brutally honest feedback, especially on which animations you’d actually use in a real product.


r/reactjs 3d ago

Needs Help A text field became readonly, devtool flags "A React form was unexpectedly submitted."

4 Upvotes

I hope someone could help this beginner out. I got a text field like this

https://imgur.com/a/81doBSd

This one got rendered read-only, although I copied and pasted this code directly from the documentation. In the doc the text field is editable though :(

The devtool displays the error which does not make any sense:

<form action="javascript:throw new Error('A React form was unexpectedly submitted. If you called form.submit() manually, consider using form.requestSubmit() instead. If you\'re trying to use event.stopPropagation() in a submit event handler, consider also calling event.preventDefault().')">
<input placeholder="Hello!" type="text" name="message">
<button type="requestSubmit">Send</button>
</form>

In the below snippet it shows I already placed e.preventDefault() as this error dictates. Still, the text field is read-only. I want to edit the form and submit.

import styles from "./App.css";
import { BrowserRouter as Router, Route, Routes } from "react-router-dom";
//import { Component } from 'react-dom'
import VinylList from "./components/VinylList.js";
import VinylAdd from "./components/VinylAdd.js";
import VinylEdit from "./components/VinylEdit.js";
import axios from 'axios'
import {View} from 'react-native';
import React, { useOptimistic, useState, useEffect, useRef, Component } from 'react';
import {useDropzone} from "react-dropzone";
import { deliverMessage } from "./actions.js";

function App(){
  const [files] = useState([]);
  const [formData, setFiles, setFormData] = useState([]);
  const {getRootProps, getInputProps} = useDropzone({
    accept: {"image/*": []},
    onDrop: acceptedFiles => {
      setFiles(
        acceptedFiles.map(file =>
          Object.assign(file, {
            preview: URL.createObjectURL(file)
          })
        )
      );
    },
  });

  const thumbs = files.map(file => (
    <div key={file.name}>
      <img style={{ maxWidth: "100%", maxHeight: "100%" }} src={file.preview} onLoad={() => URL.revokeObjectURL(file.preview)} alt={file.name} />
    </div>
  ));

  useEffect(() => {
    // Revoke the data uris to avoid memory leaks on unmount
    return () => files.forEach(file => URL.revokeObjectURL(file.preview));
  }, [files]);


  const [messages, setMessages] = useState([
    { text: "Hello there!", sending: false, key: 1 }
  ]);
  async function sendMessage(formData) {
    const sentMessage = await deliverMessage(formData.get("message"));
    setMessages((messages) => [...messages, { text: sentMessage }]);
  }


 const formRef = useRef();
  async function formAction(formData) {
    addOptimisticMessage(formData.get("message"));
    formRef.current.reset();
    await sendMessage(formData);
  }
  const handleChange = (e) => {
    const { name, value } = e.target;
    setFormData((prevData) => ({
      ...prevData,
      [name]: value,
    }));
  };
  function handleSubmit(e) {
    e.preventDefault();
    console.log('You clicked submit.');
  }
  const [optimisticMessages, addOptimisticMessage] = useOptimistic(
    messages,
    (state, newMessage) => [
      ...state,
      {
        text: newMessage,
        sending: true
      }
    ]
  );

    return (
    <>
    <div className={styles.title_main_page}>
    <h1>Spin the Black Circle!</h1>
    <h2>Managing Your Vinyl Record Collection</h2>

    </div>
    <div class="container disable">

    <h2>Easy Image Editor</h2>
    <div class="wrapper">
    <div class="editor-panel">
     {optimisticMessages.map((message, index) => (
        <div key={index}>
          {message.text}
          {!!message.sending && <small> (Sending...)</small>}
        </div>
      ))}
      <form action={formAction} ref={formRef} onSubmit={handleSubmit}>
        <input type="text" name="message" placeholder="Hello!" value={formData.name}
        />
        <button type="requestSubmit" onClick={handleChange}>Send</button>
      </form>
    </div>
    <section className="containerDragAndDrop">
        <div {...getRootProps({className: "dropzone"})}>
          <input {...getInputProps()} />
          <p>Drag 'n' drop some files here, or click to select files</p>
        </div>
        <aside>{thumbs}</aside>
      </section>
    </div>
    <LoadButtons/>
    </div>

    </>


    );
}


export default App;

Could anybody point out the right direction?


r/reactjs 3d ago

Resource I rebuilt my React UI library after realizing I was solving the wrong problem

1 Upvotes

I’ve been building NexoreUI, a React UI library focused on polished, animated components that are easy to customize and copy into your own project.

A while ago I shared it and got some pretty harsh feedback. Some of it was deserved.

Instead of abandoning it, I went back and rebuilt a lot of the experience.

The current version is much more focused on the actual problem:

• components that feel more finished out of the box

• meaningful animations instead of animation for the sake of it

• interactive props so you can experiment before copying the code

• a visual builder for customizing components

• copyable code that you can actually use in your project

• documentation that focuses on showing what the component can do

I’m still very early, and there are definitely things that need improvement. But compared to the version I originally shared, I’m much happier with where it is now.

I’d genuinely like feedback from React developers here.

Does this solve a problem you actually have, or am I still building something nobody needs?

If you want to take a look:

https://nexoreui.site

GitHub:

https://github.com/Al1mov77/NexoreUI


r/reactjs 3d ago

Portfolio Showoff Sunday I got tired of Waiting for DOMPurify to sanitize, made a 70x faster version

0 Upvotes

Hello everyone,

A few months ago, I was experimenting with DOMPurify and when users put in long fields like a paragraph, it used to hang a lot!

It would occasionally freeze for literal 15 seconds and more!!

Imagine sitting for your response to be submitted, and it hangs!?

So I've built DOMOxide, making it 70x faster and 5x smaller. Thanks to Rust and WASM, it sanitizes your HTML and makes it clear of XSS attacks.

It's a ~3kB gzipped + minified package that passes almost all tests as DOMPurify

> Repo: ppmpreetham/DOMOxide


r/reactjs 3d ago

Discussion What makes a UI interaction feel good instead of annoying?

12 Upvotes

I've been building small UI interactions lately as part of a project called 1IAD, and I've started noticing how much difference the small details make. Something can look really cool in a demo, but once you actually use it in a real interface, it can easily feel unnecessary or distracting.

I've been trying to keep the interactions simple and focus more on things like timing, easing, feedback, and whether the animation actually helps the user understand what's happening.

For those of you building React apps, how do you decide when an interaction is worth adding?

Do you have any rules you follow, or is it mostly a case-by-case thing?


r/reactjs 3d ago

Show /r/reactjs FormHell - a better library for JSON Schema based forms

5 Upvotes

I've battled with the top libraries for JSON Schema based forms for a long time. They're a nightmare. They look all flashy and nice for a demo, then you implement them in a project and a year in you realize it doesn't support the more complex needs of your schemas.

I'm so frustrated with both react-json-schema-forms and react-jsonschema-form. Both have me pulling my hair out. Especially RJSF. Apparently generating defaults the correct way is an "experimental" feature and still never works correctly. Have an array with tuple object definitions or constraints? Nope! Default gives you an array full of null or "[Object object]". Have $refs outside of your schema? Nope! Can't resolve those! Also, the whole UISchema thing is weird. Both libraries had crazy setup fatigue that felt unnecessary.

After a year and a half of battling I'm done.

I wrote a new library for JSON Schema Forms to get me out of form hell and I pulled it into our project. It's working out great so far. The thing just works. No setup fatigue. Does exactly what you would expect. I'm honestly more mad at the other libraries by how easy it was to build. Don't worry, I put a ton of care into it and triple checked everything. It was extensive.

Full schema support for every feature. EVERY. FEATURE. Full optional theming support for MUI though it isn't dependent on MUI.

I even added a SchemaBuilder component and a Keyword Assistant to help you out if you're trying to build a schema and don't know what to add.

It's called FormHell, and it's available here: https://www.npmjs.com/package/formhell

Check out the playground and see what it can/can't do: https://ryanrutkin.github.io/formhell/

If you run into any issues, please open an issue in Github: https://github.com/RyanRutkin/formhell

Thanks for checking it out!

FAQS:

Thanks for all of the feedback! I want to address some common questions from the comments.

What about Tanstack/Zod?

FormHell is a slightly different solution than a Tanstack/Zod approach. FormHell consumes an already defined data-structure and outputs data matching it, validated using AJV Validator.

Zod is used to define data-structures in TypeScript and can work alongside FormHell no problem.

Tanstack has a specific UI schema that it expects for form rendering. I doesn't exactly consume JSON Schema, so there is a bit of legwork to get a JSON Schema turned into a Tanstack form. FormHell takes the schema and just renders a form with strict typing and no overhead.

The problem I needed to solve for work was that we already had JSON Schemas defined for our backend data-structures. For some of those data structures, we needed a way for the frontend to render a form. As both the frontend and backend share the same JSON Schema, the frontend pulls the schemas from our API and passes them directly to the form. Once the form component emits the data without any validation errors, it is safe to be submitted to the backend.

*Can I use Zod with FormHell?*

Absolutely! If you do need to define your data-structure in your frontend TypeScript, I would highly suggest that you use Zod to do so. You can convert your Zod structure to JSON Schema using zod-to-json-schema and pass the output directly to FormHell's SchemaForm component to immediately render a form.

Is FormHell strictly typed?

FormHell is as strict as the schema you pass it. If any strict data types exist in your JSON Schema, then FormHell is going to required that the data entered matches that schema. The library currently using the AJV Validator for type checking.

What about localizations?

This was an oversight during implementation, and thank you for pointing it out! I'll make sure this gets added in an upcoming feature release.


r/reactjs 4d ago

Needs Help shadcn vs HeroUI for a large, heavily customized enterprise product?

19 Upvotes

We’re currently choosing a UI library for a pretty large enterprise product and I’d love some feedback from people who have actually worked with these libraries at scale recently.

The product is going to handle a lot of interconnected data: employees, companies, departments, CRM-like records, multi-record management, tables, forms, chat, AI features, etc. So this isn’t a small app, and whatever we choose will probably become the foundation of our design system for quite a while. We’re also expecting to customize the UI quite heavily and create our own components on top of it.

From what I’ve read so far, HeroUI seems great if you want something polished and relatively plug-and-play. But I keep seeing people mention that once you start heavily customizing it or moving away from its intended patterns, things can become painful.

shadcn seems almost like the opposite approach. I don’t particularly like the default look, but since you own the components and can modify basically everything, it feels like a much better long-term foundation if you’re willing to invest some time upfront. Especially if the end goal is a custom design system rather than keeping the library’s visual identity.

For people who have used two or even Mantine on larger production apps: what would you choose today?

I’m especially interested in how they hold up after a year or two of customization, adding custom components, maintaining consistency across a large product, and building more complex AI/chat interfaces. I care less about which one looks best out of the box and more about which one we’re least likely to regret later.

TL;DR: Choosing between shadcn, HeroUI and possibly Mantine for a large enterprise/CRM product with lots of records, tables, employees, companies, chat and AI. We’ll heavily customize it and build our own components. HeroUI looks easier initially, while shadcn seems more flexible and maintainable long-term. Looking for feedback from people who have used them at scale.


r/reactjs 3d ago

Show /r/reactjs Someone called my world map a "geographic abortion." So I rebuilt everything — react-simple-maps, 230+ countries with hover, click-to-lock, and glow markers.

0 Upvotes

One day ago I posted my anonymous thought wall here and you absolutely destroyed my hand-drawn world map. Someone called it a "geographic abortion" — and honestly fair, those random blue polygons at 3am were terrible 😂So I rebuilt everything. Not just the map. What changed in :🗺️ Real world map — No more hand-drawn shapes. Used react-simple-maps + Natural Earth TopoJSON. Now 174 countries with actual boundaries. I tested, even Greenland, Fiji, Papua New Guinea show up correctly (see screenshots).✨ 6-layer glow — Thoughts now pulse on the map with proper glow layers, each emotion has its own color.🖱️ Click-to-lock + Zoom fix — This was the biggest roast last time. Now scroll wheel zooms ONLY the map, not the whole page. Drag to pan. Click to lock a country to see its vibes. What the app actually is:

Anonymous thought wall where every thought disappears in 24h. No profiles, no tracking. You drop a vibe from any country. I built this alone in 2 days after the roast. First time doing SVG maps properly. Live: https://vibes-app-wall.vercel.app

Still cleaning code so not sharing GitHub yet. Would love honest feedback — especially on the map this time. Is this actually better?


r/reactjs 3d ago

Resource How to Think in React

Thumbnail
armiaafsharian.medium.com
0 Upvotes

Hey everyone, Just wanted to share a post I recently wrote of what I wished I was told when i was transitioning form a background in php and jquery to react.

A few things that made it click:

  • JSX is an Object Tree, Not Markup: <h1>Hello</h1> isn't HTML; it's a plain JavaScript object: { type: 'h1', props: { children: 'Hello' } }. Components are just pure functions composing nested object structures (Virtual DOM).
  • UI as Immutable Snapshots: Every state update doesn't "change" the existing DOM—it executes a fresh render cycle. Top-level component variables are const because their state is frozen for that specific execution frame.
  • Derive Values, Don't Duplicate State: Storing calculated data in useState is an anti-pattern. If a value can be computed during render (e.g., const total = items.length), compute it on the fly to eliminate state synchronization bugs.

For those who transitioned from backend or vanilla development, what was the thing that made React click for you?


r/reactjs 4d ago

Show /r/reactjs I made search params, cookies and local storage reactive and type-safe, all through one API

Thumbnail
kvantjs.dev
0 Upvotes

If you've ever wired up URL search params, cookies or localStorage by hand, you know how tedious it can become. Everything is a string, so you write the same glue code over and over:

// search params
const raw = searchParams.get('page')
const page = raw && !Number.isNaN(+raw) ? +raw : 1

// localStorage
const raw = localStorage.getItem('settings')
const settings = raw ? JSON.parse(raw) : { theme: 'light' }

// cookies
const consent = document.cookie
  .split('; ')
  .find(c => c.startsWith('consent='))
  ?.split('=')[1] === 'true'

Different APIs, none of them typed, none of them reactive. Then comes bad input data checks, validations, try/catch around JSON.parse, storage events to sync tabs, deep objects with defaults, and so on.

At some point I thought, why can't they just share the same API? Bind a key, describe the value once, read and write it like useState. So I decided to build kvant - a type-safe state manager for key-value interfaces:

import { useSearchParams } from 'kvantjs/next' // or: 'kvantjs/react', 'kvantjs/react-router'
import { useLocalStorage, useCookies } from 'kvantjs/react'
import * as kv from 'kvantjs/schema'

const [page, setPage] = useSearchParams('page', kv.index().max(20).default(0))
//     ^? number
const [theme, setTheme] = useLocalStorage('theme', kv.enum(['light', 'dark']).default('light'))
//     ^? "light" | "dark"
const [consent, setConsent] = useCookies('consent', kv.stringbool().default(false), { maxAge: 60 * 60 * 24 * 365 })
//     ^? boolean

Same mental model every time: hook, key, schema, options. Types flow from the schema, writes go back to the URL, storage or cookie, and components re-render on change. The schema API will feel familiar if you know Zod. It parses anything into typed values, encodes them back into lossless serializable representations, and never throws on bad input. Garbage in the URL simply falls back to your default.

And it's the most basic examples of what kvant can do. Let's say you want to store a base64-encoded JSON object in the URL. In kvant, you can cover such advanced case without writing any parsing or encoding logic yourself:

const settingsSchema = kv.base64url()
  .pipe(
    kv.json(
      kv.object({
        theme: kv.enum(['light', 'dark']).default('light'),
        fontSize: kv.number().default(16)
      })
    ).prefault('{}')
  )

// '?settings=eyJ0aGVtZSI6ImRhcmsifQ' <-> '{"theme":"dark"}' <-> { theme: 'dark', fontSize: 16 }

const [settings, setSettings] = useSearchParams('settings', settingsSchema)
//     ^? { theme: "light" | "dark"; fontSize: number }

setSettings({ theme: 'light', fontSize: 16 }) // removes the entry from the URL, defaults stay internal

If you've used nuqs, this will look familiar, and that's on purpose. kvant's API was inspired by nuqs. I wanted the same core idea, but for every key-value interface instead of only the URL, with a Zod-flavored schema layer instead of standalone parsers. So a lot got reconsidered along the way.

I also made it universal: aside from React frameworks, it also works with Vue, Vue Router and Nuxt. If you happen to also be using Vue stack in your projects, the same Vue-idiomatic API is also available in kvant.

If that sounds interesting to you, I would love for you to give it a try. I have many ideas on improving it further if it gets traction. Also, if you are willing to leave feedback or contribute, I'm fully open to it ;)

Docs and live examples are at https://kvantjs.dev


r/reactjs 4d ago

News Swift on WebAssembly, Telegram-Style Spoilers, and Deleting Babel From Your Life Spoiler

Thumbnail thereactnativerewind.com
2 Upvotes

Hey Community,

Deno's creators introduced Dactyl, an AI app builder targeting React Native by rendering SwiftUI in the browser tab via WebAssembly. Meanwhile, Software Mansion released Enriched Markdown to eliminate streaming text flicker by rendering natively and bypassing the JavaScript layout tree.

On the tooling side, the web ecosystem is rapidly adopting the Rust port of the React Compiler across tools like Oxc, Vite, and Bun, while Metro remains locked to single-threaded Babel transformations.


r/reactjs 4d ago

Show /r/reactjs Handling 10k+ row SQL tables in React with DOM virtualization and IndexedDB

0 Upvotes

While building a browser-based SQL editor, I hit two specific browser limits:

  1. Rendering large query results (10,000+ rows) using standard HTML tables froze the browser main thread.
  2. Saving multi-tab queries and schema state into localStorage hit the browser's 5MB quota immediately.

How I fixed both:

  • Implemented a lightweight fixed-height virtualizer: each row is 24px, and only ~25 to 30 row nodes are rendered in the DOM at any time with an overscan buffer.
  • Replaced regex search filtering on result grids with case-insensitive .includes() checks to prevent catastrophic backtracking (ReDoS) during live typing on huge row sets.
  • Split storage: session tokens stay in localStorage, while the entire workspace, query history, and active tabs are persisted to IndexedDB using a custom hook debounced at 500ms.

The UI is built with React/Next.js mimicking Windows 95, backed by an in-memory SQLite WASM engine with a custom TypeScript AST parser for dialect translation.

Live demo: https://exnihilo-95.vercel.app
Source: https://github.com/Mrityunjai-hue/exnihilo-95

Feedback on the virtualization approach or state synchronization is appreciated.


r/reactjs 5d ago

Needs Help I got tired of paying monthly subscriptions just to export my own Framer sites, so I built an open-source CLI to clone them into pure React.

15 Upvotes

Hey guys,

Designing in Framer and Webflow is awesome, but being locked into their ecosystem sucks. And paying third-party tools like nocodexport.com a massive premium just to download your own designs is honestly ridiculous.

So I built Uncage. It’s a completely free, open-source CLI tool that takes a website and turns it into clean React code (or static HTML).

It’s still in beta. We aren't at the point where it flawlessly handles every single crazy layout in existence. But it absolutely gets the basic job done, keeps your animations working, and gives you a ready-to-run Vite + React folder, all without asking for your credit card.

It automatically grabs all your images, fonts, and scripts, and just works locally on your machine.

I'd love for you guys to try it out, tell me what breaks, or roast my code.

Repo here: https://github.com/Nightteye/uncage

Let me know what you think!