/r/reactjs
A community for discussing anything related to the React UI framework and its ecosystem. Join the Reactiflux Discord (reactiflux.com) for additional React discussion and help.
A community for learning and developing web applications using React by Facebook.
Interested in building mobile apps using React Native? Check out /r/reactnative!
If you believe someone is violating the code of conduct, please report the post or message, or contact the mods.
Be kind to your fellow human. There’s no need to be mean or rude, keep unstructured critique to a minimum. When providing help, answer their question before making stylistic or tool suggestions.
We all started somewhere, and we're all allowed to be who we are. We are committed to providing a friendly, safe and welcoming environment for all, regardless of level of experience, gender identity and expression, sexual orientation, disability, neurodivergence, race, ethnicity, physical attributes, religion, nationality, or other aspect of identity.
reddit has a long history of intentionally offensive usernames, but not here. Names that detract from a friendly, safe and welcoming environment for all will be addressed.
Every design or implementation choice carries a trade-off and numerous costs. There is seldom a single right answer, and there are valid reasons to choose between a range of tradeoffs between tools, approaches, and patterns.
If you join this community to take value rather than contribute, the community will quickly react as though you are an intruder. If you have a body of content you'd like to promote, our recommended way of doing so is to be an active and positive member of the subreddit. If someone has a question that you've created an external answer to, we'd love if you share it!
reddit is a great format, but sometimes you need to chat in real time. Reactiflux is our recommended Discord community.
Get Your Next Project Idea Here
Like building things? People want to pay you to build things! Join Reactiflux and check out #job-board (and the rules!)
reactjs
on Stackoverflowirc.freenode.net #reactjs
/r/reactjs
Is there any way to declare components inside a closure without breaking the rules of hooks?
Hi r/reactjs 👋
I’m excited to share Reddit Stats, a tool I built for analyzing Reddit user activity.
Here’s what you can do:
It’s designed for anyone curious about user behavior on Reddit. I’d love to hear your thoughts or suggestions for improvement.
Feel free to check it out here: Reddit Stats. Thanks in advance for your feedback! 😊
I made a personal modal that takes as props: text, showModal and setShowModal useStates. so i need to create a useState and pass it as props.
With the usual way i see perople make a custom ErrorBoundary is they make it a class component (therefore i cant use useState). And im told class components are not recommended anymore.
Whats the best way to properly setup a global error handler that will display a custom modal and keep the rest of the page as it is?
Hey guys, As full stack frameworks like Nextjs and Remix are getting popular day by day, will you still choose them if you already have a backend( in js or any other language) and just want to develop a frontend for it And if yes then why?
In my project, I'm using Sonner (https://sonner.emilkowal.ski/) and I want to add my own custom enter and exit toast animation. By default, Sonner will play a slide in and out animation, and attempting to override this with a custom animation isn't giving me much success. If anyone can help, that would be greatly appreciated. Below is my code snippet:
<Toaster
position="top-left"
offset={17}
pauseWhenPageIsHidden
icons={{
success: <i className="fa-solid fa-circle-check"></i>,
info: <i className="fa-solid fa-circle-info"></i>,
warning: <i className="fa-solid fa-circle-exclamation"></i>,
error: <i className="fa-solid fa-circle-xmark"></i>,
loading: <Loader size="sm" />
}}
toastOptions={{
unstyled: overrideAllClasses,
classNames: {
toast: getClassName(
'p-3 bg-zinc-800 text-white border-none select-none',
toastClassName,
overrideToastClassName
),
title: getClassName(
'font-helvetica text-lg tracking-wider leading-5',
titleClassName,
overrideTitleClassName
),
description: getClassName(
'font-light text-sm tracking-wider',
descriptionClassName,
overrideDescriptionClassName
),
icon: getClassName(
'text-2xl mr-3',
iconClassName,
overrideIconClassName
),
},
}}
/>
I have been trying to find a video tutorial, book, or online course to help me take my React skills to the next level. Most of the YouTube tutorials I see now are very surface level, and all of the longer more "complex" project videos I've seen are just a "copy what I do" type of video, with no explanation or context as to why this is being done this way.
Does anybody here know of a good tutorial, paid or unpaid, that can help me understand best practices when using React to build big, complex, enterprise-level applications?
P.S: if this has been answered previously on this subreddit, please refer me to the post before taking this down, thank you.
After upgrading from react 18.3 to react 19, I noticed that loading components with React.lazy seem to be taking longer time in v19 than in v18.
I had my lazily-loaded component wrapped in Suspense, but did not provide a fallback component to Suspense to show while it was executing React.lazy. Since I was using a service worker to precache the static assets, the network request resolved almost instantaneously; and the lack of a fallback component wasn't visible. After upgrading to react 19, I started seeing a flash of a white screen. Surprised, I examined the performance trace; and what I saw there, surprised me even more.
Below is a link to a trace that I annotated with several labels.
https://i.imgur.com/MwGl3ef.png
At around 1000ms mark, I am clicking on a link to navigate to a different screen. The component for the other screen is wrapped in React.lazy. You can see that the static files are requested and delivered almost immediately. Then a bit of work happens, and then — nothing, for about 250 milliseconds. The main thread is doing nothing. Then it finally kicks in, and after a bit of work, ships a frame. These 250 milliseconds Suspense, lacking a fallback component, is showing a blank screen.
These 250 milliseconds of no work seem shockingly wasteful. It's not like react is yielding to higher-priority UI tasks, which is what "time slicing", aka "concurrent mode", aka "concurrent features", aka the reason for react fiber used to be all about — it is just not doing any work.
This is mostly a rant. I know that I should have provided a fallback for Suspense, and it is my fault that without it, I am seeing flashes of white screen. But also, I am curious: does any of you know how react scheduler works, and why it could have allocated 250 milliseconds of time until the next task?
Hey gang.
Is anyone using this sort of setup in production?
We currently have this but use node/npm for local dev. I’m not really even sure much would change, but I do know that I hate managing a tsconfig
.
Any great quality of life benefits? And gotchas?
Hey!
I’d like to share Draw, a project I’ve been working on. I built Draw because I needed a way to be able to sync the work that I did in Exaclidraw between my computers. It uses Supabase as the Backend as I needed an easy way to get Auth and Storage and Supabase was the easiest way to do all this.
If you’re looking for a tool to save your Excalidraw sketches or want to explore the code, check it out! I’d love to hear your feedback and suggestions.
Deployment: https://draw.macintushar.xyz/
Repo: https://github.com/macintushar/draw
Controller.tsx
import { useState } from "react";
import Title from "./Title";
import axios from "axios";
import RecordMessage from "./RecordMessage";
const Controller = () => {
const [isLoading, setIsLoading] = useState(false);
const [messages, setMessages] = useState<any[]>([]);
function createBlobURL(data: any) {
const blob = new Blob([data], { type: "audio/mpeg" });
const url = window.URL.createObjectURL(blob);
return url;
}
const handleStop = async (blobUrl: string) => {
setIsLoading(true);
// Append recorded message to messages
const myMessage = { sender: "me", blobUrl };
const messagesArr = [...messages, myMessage];
// convert blob url to blob object
fetch(blobUrl)
.then((res) => res.blob())
.then(async (blob) => {
// Construct audio to send file
const formData = new FormData();
formData.append("file", blob, "myFile.wav");
// send form data to api endpoint
await axios
.post("http://localhost:8000/post-audio", formData, {
headers: {
"Content-Type": "audio/mpeg",
},
responseType: "arraybuffer", // Set the response type to handle binary data
})
.then((res: any) => {
const blob = res.data;
const audio = new Audio();
audio.src = createBlobURL(blob);
// Append to audio
const rachelMessage = { sender: "rachel", blobUrl: audio.src };
messagesArr.push(rachelMessage);
setMessages(messagesArr);
// Play audio
setIsLoading(false);
audio.play();
})
.catch((err: any) => {
console.error(err);
setIsLoading(false);
});
});
};
return (
<div className="h-screen overflow-y-hidden">
{/* Title */}
<Title setMessages={setMessages} />
<div className="flex flex-col justify-between h-full overflow-y-scroll pb-96">
{/* Conversation */}
<div className="mt-5 px-5">
{messages?.map((audio, index) => {
return (
<div
key={index + audio.sender}
className={
"flex flex-col " +
(audio.sender == "rachel" && "flex items-end")
}
>
{/* Sender */}
<div className="mt-4 ">
<p
className={
audio.sender == "rachel"
? "text-right mr-2 italic text-green-500"
: "ml-2 italic text-blue-500"
}
>
{audio.sender}
</p>
{/* Message */}
<audio
src={audio.blobUrl}
className="appearance-none"
controls
/>
</div>
</div>
);
})}
{messages.length == 0 && !isLoading && (
<div className="text-center font-light italic mt-10">
Send Rachel a message...
</div>
)}
{isLoading && (
<div className="text-center font-light italic mt-10 animate-pulse">
Gimme a few seconds...
</div>
)}
</div>
{/* Recorder */}
<div className="fixed bottom-0 w-full py-6 border-t text-center bg-gradient-to-r from-sky-500 to-green-500">
<div className="flex justify-center items-center w-full">
<div>
<RecordMessage handleStop={handleStop} />
</div>
</div>
</div>
</div>
</div>
);
};
export default Controller;
RecordMessage.tsx
import { ReactMediaRecorder } from "react-media-recorder";
import RecordIcon from "./RecordIcon";
type Props = {
handleStop: any;
};
const RecordMessage = ({ handleStop }: Props) => {
return (
<ReactMediaRecorder
audio
// onStop={()=>{handleStop}}
onStop={handleStop}
render={({ status, startRecording, stopRecording }) => (
<div className="mt-2">
<button
onMouseDown={startRecording}
onMouseUp={stopRecording}
className="bg-white p-4 rounded-full"
>
<RecordIcon
classText={
status == "recording"
? "animate-pulse text-red-500"
: "text-sky-500"
}
/>
</button>
<p className="mt-2 text-white font-light">{status}</p>
</div>
)}
/>
);
};
export default RecordMessage;
export default function SideBar() { const [isOpen, setIsOpen] = useState(false);
const toggleSidebar = () => {
setIsOpen(!isOpen);
};
return (
<div>
<div className={`sidebar ${isOpen ? 'open' : ''}`}>
<div className="logo-details">
<img src="/Logo.png" alt="Logo" className="sidebar-logo icon" />
<div className="logo_name">Schedut</div>
<i className='bx bx-grid-alt' id="btn" onClick={toggleSidebar}></i>
</div>
<ul className="nav-list">
<li>
<i className="bx bx-search" onClick={toggleSidebar}></i>
<input type="text" placeholder="Search..." />
<span className="tooltip">Search</span>
</li>
<li>
<Link to="/Routine">
<i className='bx bx-analyse'></i>
<span className="links_name">Routine</span>
</Link>
<span className="tooltip">Routine</span>
</li>
<li>
<Link to="/ContinuousCalendar">
<i className='bx bx-calendar' ></i>
<span className="links_name">Calendar</span>
</Link>
<span className="tooltip">Calendar</span>
</li>
<li>
<Link to="/ToDo">
<i className='bx bx-task' ></i>
<span className="links_name">To-Do</span>
</Link>
<span className="tooltip">To-Do</span>
</li>
<li>
<Link to="/TimeLine">
<i className='bx bx-objects-horizontal-right bx-rotate-180' ></i>
<span className="links_name">Timeline</span>
</Link>
<span className="tooltip">Timeline</span>
</li>
<li>
<Link to="/Maps">
<i className='bx bx-map' ></i>
<span className="links_name">Maps</span>
</Link>
<span className="tooltip">Maps</span>
</li>
<li>
<Link to="/Settings">
<i className="bx bx-cog"></i>
<span className="links_name">Setting</span>
</Link>
<span className="tooltip">Setting</span>
</li>
<li className="new-task">
<Link to="/NewTask">
<i className='bx bx-add-to-queue' ></i>
<span className="links_name">New Task</span>
</Link>
<span className="tooltip">New Task</span>
</li>
</ul>
</div>
<section className="home-section">
<div className="text">Dashboard</div>
</section>
</div>
);
}
export default function App() { return ( <div className='main-container'> <SideBar> <Routes> <Route path="/" element={<Dashboard />} /> <Route path="/Routine" element={<Routine />} /> <Route path="/ContinuousCalendar" element={<ContinuousCalendar />} /> <Route path="/ToDo" element={<ToDo />} /> <Route path="/TimeLine" element={<TimeLine />} /> <Route path="/Maps" element={<Maps />} /> <Route path="/Settings" element={<Settings />} /> <Route path="/NewTask" element={<NewTask />} /> </Routes> </SideBar> </div> ); }
I believe my mistake is coming from here. My problem is that regardless of what button on my sidebar I press, only the dashboard element will render outside of the sidebar even though it does take me to the correct page the button is linked too. I am not known for structuring my questions correctly, so im trying to include all of the code necessary for someone to potentially help me this time.
I understand that Strict Mode mounts components twice, and then unmounts the first one. It also runs initializers twice, for example, when you pass a closure to useState
. So when given the following component:
function Foo() {
console.log('a');
const [ state, setState ] = useState(() => {
console.log('b');
return 0;
});
useEffect(() => {
console.log('c');
return () => {
console.log('d');
}
}, []);
return <div>Foo</div>;
}
I would expect the following order: a
, b
, b
, c
, d
, a
, b
, c
.
Instead, I am getting a
, b
, b
, a
, c
, d
, c
.
As you can see, b
is printed twice during the first mount, and then not at all during the second mount. What this means is that if I initialize some resource in b
, and then clean it up in d
, the cleanup function is executed before the component is properly mounted.
How am I supposed to work around this? Am I the only one who finds React's behavior here baffling?
Our company’s react application now got a moment to refactor its unefficient data fetching. I asked to use tanstack react-query, my team’s tech lead and manager don’t want to add additional libraries if we don’t have a significant value from using it. We updated our app’s react to 18.2 and react-router-dom to 6.4 something. I feel if we can use react-router’s loader with combining react-query, it can achieve best performance. Our application will have a dashboard with a lot of table information with pagination, so react-query’s infiniteQuery will be help us for infinite-scrolling as well. But wonder how other company do data fetching? Just useState and useEffect dancing? Or only loader something like react-router?
Hi everyone,
I’m excited to share a new tutorial where I guide you through creating a simple app for uploading files to a Distributed Storage Network using Autonomy's Auto-Drive API. We start by forking the RadzionKit repository to quickly set up a Next.js boilerplate, then dive into managing API keys, handling file uploads, and implementing features like pagination and file management.
Whether you’re exploring decentralized storage or looking to enhance your Next.js projects, I hope this video provides valuable insights and practical steps.
💻 Explore the source code on GitHub
I’d love to hear your thoughts and feedback. Happy coding!
#AutoDrive #Nextjs #WebDevelopment #OpenSource
I am using jwt and in frontend my session expires as my access token expires and don't know how to keep the user logged in. I tried using axios interceptors for 401 and requesting post request on my /refreshAccessToken endpoint but nothing happens
I’m working on an idea and need some input from the community. Here’s the challenge:
I want to build a React app where features can be toggled on/off dynamically—but with a twist. The idea is that the backend decides which features are enabled, and only those features are included in the final React code.
Here’s how I’m imagining it:
This could potentially make the app lighter, faster, and more secure (since disabled features wouldn’t exist in the delivered code).
Questions:
I’d love to hear your thoughts, especially if you’ve dealt with dynamic apps, feature toggling, or backend-driven UI generation.
The website is meant for people that look for jobs on HackerNews "Who's Hiring" threads and want to focus more on fresh ads and companies, or to quickly look up ad history of any company.
Github repository: https://github.com/nemanjam/hn-new-jobs
Demo website: https://hackernews-new-jobs.arm1.nemanjamitic.com
I used Algolia API as a data source, along with scheduled task that parses new threads few times at the beginning of each month. The extracted data is then stored in SQLite database for fast querying, and the results are cached with Keyv for faster page responses. I will see in the future how much traffic the website receives and if this stack is performant enough. For the website I used Next.js app with default ShadcnUI components and charts. I just wanted a quick functional prototype to test how much public interest is there for an app with functionality like this.
If you are interested in more implementation details you can find them in the Readme file on Github.
The project is free and open source. Feel free to use, self-host, fork and modify, and contribute. I would love to hear your impressions and suggestions and look forward to discussing features and technical details.
react-router vs react-router-dom , when to use one or the other
There are a few libraries that would significantly reduce my productivity if they didn't exist. What are your favorite libraries that let you focus on the fun stuff and forget about having to write boring infrastructure?
Per a redditor's request, I have extracted my boilerplate for a full-stack next
repo, with typed contracts from the database to the front-end.
The template uses a separate API to unlock next
's caching features and circumvent the limitations of next
for backend code. It also demonstrates using minimalist express
-like patterns but typed (via fastify
+ zod
) instead of relying on maximalist solutions like NestJS.
https://github.com/chriskuech/fullstack-monorepo-template
Let me know your thoughts or if there's anything else you'd like to see.
What is the proper way to handle no internet connection in a reactJS app because navigator is not working.
This is my code.
const [isOnline, setIsOnline] = useState(navigator.onLine);
const handleOnlineDM = () => {
setIsOnline(true);
console.log("Online");
}
const handleOfflineDM = () => {
setIsOnline(false);
console.log("Offline");
}
useEffect(() => {
const handleOnline = () => handleOnlineDM();
const handleOffline = () => handleOfflineDM();
window.addEventListener('online', handleOnline);
window.addEventListener('offline', handleOffline);
return () => {
window.removeEventListener('online', handleOnline);
window.removeEventListener('offline', handleOffline);
};
}, []);
I am working on setting up RTK Query for an app at my company. I have two sets of endpoints I need to hit on our backend, one set which requires authentication for a restricted portion of the site and one set which does not for a public facing side. This seems like a fairly common use case and I was wondering if there are any best practices around how to handle this scenario?
I've seen conflicting recommendations on the use of multiple APIs. My understanding from the docs and reading comments on here is that you should only ever have one API for your site, but when researching this question I came across recommendations to have one API for the public portion and one API for the authenticated portion, which I guess makes sense from a practical sense if I am writing a custom baseQuery
to handle tokens and such, but it seems like that would violate the previous best practices I understood.
Does anyone know if there is a better way to separate these two?
Hello, does anyone have a good calendar library for events? I need to be able to show events, edit them etc. (Something like google calendar) I am using shadcn, so I would like something in a similar style. I looked at big calendar and full calendar, but I didn't like the look of either of them.
I have been applying the composite component pattern, however I have come across the following question, should I manage each component in its own file or in the same one. For example, a Card component has CardHeader, CardContent and CardFooter, these are small components that only add styles, should I separate them or manage them in a single Card file?
Hey guys. I want to build a react app where you can login to your google account, pick a date, add description and send it to google calendar. What npm library do you recommend to handle google calendar api? Tbh
My app is basically a dashboard with multiple widgets available - for this I went with an app for the dashboard and libraries for the widgets. Basic logic is that the dashboard passes data to the widget and the widget displays it in a selected form. There can be multiple widgets within one dashboard.
The problem I'm facing now is that if I have the same type of the widget in a dashboard, it just displays one dataset instead of two separate ones, even though the widget receives and contains different data.
As to more detailed background work - the flow is as follows:
displaying the widgets:
{widgetsInWorkspace.map(({ id, query, title }: Widget) => (
<div key={id}>
<ChartWrapper
widgetId={id}
query={query}
/>
</div>
))}
inside chart widget:
<div key={widgetId} ref={wrapperRef}>
<ChartWidget
query={validatedQuery}
/>
</div>
I think I tried putting key attribute in every place at this point, but it doesn't help, so any help would be greatly appreciated!