/r/reactjs

Photograph via snooOG

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.

About:

A community for learning and developing web applications using React by Facebook.

Interested in building mobile apps using React Native? Check out /r/reactnative!


Code of Conduct

If you believe someone is violating the code of conduct, please report the post or message, or contact the mods.

1. Please be kind and courteous, friendly and professional

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.

2. Harassment will not be tolerated

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.

3. Avoid using an alias or display name that might be offensive

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.

4. Respect that people have differences of opinion

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.

5. Posts must conform to our guidelines

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!

  1. Demo videos must be accompanied by source code, preferably in a runnable environment like Codepen, CodeSandbox, Replit, Glitch, etc.
  2. Please save portfolios for the weekly Sunday portfolio post.
  3. Posts should be original works.
  • Please do not dump raw AI output as a post or comment. If you share something from an AI, please also include which service it came from as well as an original thought, like why the response is trustworthy or details about how you prompted.
  • This subreddit is focused on technical discussion of React, for career discussion check out /r/cscareerquestions or #jobs-advice in Reactiflux.
  • Avoid commercial activity. /r/reactjs follows the Reactiflux policy on commercial activity.
    • This is a community, not a free audience. This is not a place for prominent commercial activities such as recruiting, lead generation, marketing, market research, or other solicitation, except in posts dedicated to that purpose.
  • If the question is primarily "how do I make this code work?", please post it in the monthly "Beginner's Thread", or ask in the help channels of the Reactiflux Discord

  • New to React?

  • Kent Dodds' Egghead.io course
  • Codecademy's React courses
  • Scrimba's React course by /u/bobziroll
  • Road to React by /u/rwieruch
  • Our monthly Beginner Q&A Thread!
  • This Month in React podcast
  • React Digest

  • Chat

    reddit is a great format, but sometimes you need to chat in real time. Reactiflux is our recommended Discord community.

    Project Ideas

    Get Your Next Project Idea Here

    Jobs

    Like building things? People want to pay you to build things! Join Reactiflux and check out #job-board (and the rules!)


    Outside Reddit


    Related Subreddits

    /r/reactjs

    431,572 Subscribers

    0

    Fat components or Multiple components

    Hi, I'm studing React and I have a doubt, on react documentation they say that you need to separate the ui into components that makes sense, this causes a big component being reduced to smaller components, but I notice that when a component is more complex and realy big the component file gets realy extense with tens of components, and since I'm using typescript and need to make a type to each component the type object extends even more the file, so I'm starting to think, should I realy divide the UI that much? Or should I make more fat components and only make a subcomponent to separate logic so I don't have all the logic in the same component and so the logic stays only where I need it?

    0 Comments
    2024/11/20
    06:25 UTC

    1

    Should I use Turbopack for my Nextjs 15 project?

    I am creating a project using Next.js 15, Tailwind, Drizzle, some auth tool (any recommendations?), uploadthing, and a few that I haven't thought of yet. Coming from using Vite based tools, I don't know the limitations of using Turbopack—what is your take?

    4 Comments
    2024/11/20
    00:37 UTC

    1

    What are some good libraries for a checkbox tree component?

    Years ago I had to make a checkbox tree component at work and the best library I could find at the time was this https://www.npmjs.com/package/react-dropdown-tree-select . The default behavior of the library was what I needed: collapsable tree structure with selectable items, search, virtualization for large trees, and pills showing the currently selected items. However, the library was a pain to use, mainly because you had to wrap the component in a HOC to prevent rerenders or else any parent state change would completely wipe out the current state of the component, and because the checked state was not controlled, so you could not programmatically update the checked items from outside the component.

    Now I have to update the component and I'm looking for better libraries. I found this one https://www.npmjs.com/package/react-checkbox-tree which appears to have more usage and doesn't have some of the pain points of the other library that I mentioned. However, it still seems outdated and all of the examples are still using class components. Are there any other similar libraries you recommend that have this functionality but are more up to date? One main change I have to make is to add lazy data loading from the server for big trees of data so a library that has that functionality built in would be a huge help.

    1 Comment
    2024/11/20
    00:24 UTC

    1

    Is jest + react testing library is still the recommended way of testing react components?

    Hi!
    The last projects I worked on either didn't have component tests at all (only unit and/or e2e tests with cypress/playwright) or used Enzyme (which is dead now).
    So, if I want to introduce component tests, which setup is "popular default" right now? I suppose it is jest + react-testing-library but I know that playwright has "components testing" for react/svelte/vue as in experimental mode (didn't try it yet) and maybe there are others setups which I am not aware of.

    2 Comments
    2024/11/19
    22:36 UTC

    0

    React table where a row have certain values displayed under it as additional rows

    Basically im hoping to do something like:

    Table: Country - Population - Cities over 1m
    MainRow: Germany - 70m
    SubRow: Berlin
    SubRow: Hamburg
    SubRow: Munich
    SubRow: Cologne

    MainRow: Spain - 50m
    SubRow: Madrid
    SubRow: Barcelona

    MainRow: Italy - 60m
    SubRow: Rome
    SubRow: Milan
    SubRow: Valencia

    The subrows count will be dynamic for each row.

    Is this achievable?

    3 Comments
    2024/11/19
    20:33 UTC

    0

    tanstack/react-query: Reading and parsing getQueriesData

    New to react-query, trying to figure out a few things, namely getQueriesData

    My current "solution":

    const trades = queryClient.getQueriesData({ queryKey: ['myTrades'] });

    It does returns the data however its format is a but funky:

    [queryKey: QueryKey, data: TQueryFnData | undefined][]

    I am forced to chain the properties to get to the actual data

    (trades[0]?.[1] as any)?.count // or .trades

    I could perhaps create some kind of wrapper to quickly access that data but I am wondering if there is any better way to do it?

    5 Comments
    2024/11/19
    20:09 UTC

    6

    Should I learn JavaScript testing first before learning how to test a react app?

    I consider myself above beginner but not intermediate level engineer yet so I'm trying to hone my skills more.

    There's two courses that I have shortlisted one is JavaScript testing and the other one is React testing, which one do I go with? I'm pretty good at JS (probably beyond intermediate level) so... what do i really do? Does that matter? Do I have to able to test non react apps first before learning how to do it for react?

    Like is it kind of a pre req that you should know how to do testing in JS before learning how to do it for a react app? Should i finish JS testing course first beore jumping onto react testing course?

    Just like we cant learn TS before learning JS, is it also the case with react testing that we cant learn react testing before learning JS testing? Wont i need that JS testing background?

    Sorry if the question is silly.

    7 Comments
    2024/11/19
    19:44 UTC

    11

    Hello, I built a collection of copy/paste React components for landing pages

    I'm still working on it, but I’d love to get some early feedback and hear your thoughts.!
    badtz-ui.com

    1 Comment
    2024/11/19
    19:14 UTC

    53

    BlueSky React Developers to Follow

    I've learned a lot about react and its quirks by following current and former react core members.

    Here's an incomplete list of some those accounts on BlueSky:

    - @danabra.mov‬
    - @sophiebits.com
    - @jamie.build
    - @sebmarkbage.calyptus.eu
    - @react.dev
    - @vjeux.bsky.social
    - @threepointone.bsky.social
    - @ricky.fm
    - @brandondail.com
    7 Comments
    2024/11/19
    18:56 UTC

    6

    PDF Viewer

    Hello, I'm trying to find an alternative to pdfjs-dist, the version I was using has vulnaribility problems and when I update I have problems with my node version. I was looking for an alternative and found MuPDF, has anyone worked with it?

    I only need to render pdfs for visualization and simple navigation controls.
    I'm using node 20, with Remix

    3 Comments
    2024/11/19
    16:08 UTC

    2

    How to Handle DOMContentLoaded in React for GSAP Animations with Multiple Images?

    I'm using GSAP animations in a React project with a lot of images. In vanilla JS, I would use DOMContentLoaded to ensure the DOM is ready before running animations.

    document.addEventListener("DOMContentLoaded", () => {

    console.log("DOM fully loaded and parsed");

    // Initialize GSAP animations or custom code

    });

    But in React, useEffect seems different and doesn’t match DOMContentLoaded exactly. How can I make sure the DOM is fully loaded before triggering my GSAP animations?

    Any help is appreciated!

    1 Comment
    2024/11/19
    14:16 UTC

    3

    I can't figure out why my handleSubmit function doesn't execute

    Here is my SignupCard component that simply collects an email, password, and expects a tick for the user to agree to policies. After the user presses "Proceed to Payment", I just want it to trigger the handleSubmit function onClick, but it never logs anything to the console.

    Is anyone able to tell what's wrong here?

    At the moment, I have the onClick both in the form tag, and the button itself. If I remove onClick from the button, it doesn't submit anything, if I remove it from the form tag, it submits, and the Stripe payment button appears, but nothing logs in console from handleSubmit.

    https://pastebin.com/4iZn4P9V

    3 Comments
    2024/11/19
    13:51 UTC

    1

    Morphing SVG with FLubber and Framer Motion

    I tried to morph 2 SVGs with Flubber on click with Framer motion, it worked, but not as expected.

    The first click on the 'Hi" div triggered a change in the open state from 0 to 1, but it didn't animate the SVG. Another click event on the div did. But now the 'open' and 'progress' are not in sync.

    Here's the codesandbox link to demonstrate my working code:
    https://codesandbox.io/p/sandbox/framer-motion-morphsvg-example-forked-mhxl33?file=%2Fsrc%2FApp.tsx%3A12%2C24

    How can I solve this?

    Thanks in advance...

    0 Comments
    2024/11/19
    07:32 UTC

    0

    Simplest Implementation of 2D-turned-3D Animation in Motion (formerly Framer) w/ React?

    I’ve been storyboarding an animation that I will be implementing in Motion (formerly of Framer affinity), with useScroll() and useInView().

    Essentially, there are a number (4) of “slides” in a Hero component that the user will scroll through and reveal a sequence of marketing copy paired with an evolving animation scene.

    For one of the scenes, I want to take either the entire scene or just one (the central) element, which will consist of simple 2D shapes and lines, and animate rotation about the x-axis, such that the polyline shape the user was viewing in 2D is “revealed” to be 3D in actuality, and through this reveal they will realize that the shape (or shapes) they were viewing previously were only those shape’s projection/elevation in plan view, and after the rotation about the x-axis, that same shape (or shape) will be revealed to form a completely different shape (or shapes) in the new perspective, effectively a front elevation.

    As an example, imagine initially the user sees a cluster of rectangles drawn as a stroked path, and then after rotation about the x-axis, those rectangles are shown to be circles in this other perspective. So in reality, the shape is neither a rectangle nor a circle, but a 3-dimensional path that, when viewed from above looks like a square, and when viewed straight-on from the front, looks like a circle.

    So my question is, what is the simplest way to implement such a geometry and transformation with Motion? Is it impossible to do this without R3F? I’d rather not complicate things by making the whole thing a 3D scene, with additional dependencies, APIs, and state, if I don’t need to, but I am not sure how else it could be accomplished. Unfortunately SVG has no capability for a third dimension. Perhaps just a vanilla canvas implementation? Or would R3F just be the obvious solution here?

    Edit:

    Here's a quick sketch-up recording I made showing a similar effect of what I want to do. Basically, imagine at one point the user is looking at a square of some sort, and then the shape rotates so that you are looking at its front and now it has a "cloud" shape. This is an oversimplification of what I will be doing, but it gives the idea clearly, and isn't really that much simpler (the actual effect would feature potentially several squares turning into different shapes during the rotation)

    [imgur video](https://i.imgur.com/ZHTTlQV.mp4)

    And here is an isometric video showing the whole polyline structure in three dimensions if it helps understand it better.

    [imgur photo](https://i.imgur.com/AnfJr7e.png)

    2 Comments
    2024/11/19
    04:19 UTC

    3

    Developing cross-platform apps per best practices?

    For my next project, I want to build a cross-platform app with React. I'm looking to avoid having 2 different codebases if possible.

    Since React docs suggest using Next.js and React Native docs recommend Expo, I wanted to use Next.js with Expo. But Expo doesn't officially support Next.js' app router as far as I'm aware, which is a dealbreaker unfortunately.

    So instead, I'm now looking at Capacitor. Others seem to have good experiences with it, but it doesn't support SSR in Next.js. Do you find this a significant limitation? Anything else I should be aware of - or if you've used a different stack, do you mind sharing your experience?

    5 Comments
    2024/11/18
    21:26 UTC

    34

    yet another UI library but

    i wanted to make it stand out a bit from other component lib out there. It's also open source and what is really great is that you can install any components with shadcn cli that include hooks and multi files when needed.

    Worked on that past few weeks, hope you like it!
    https://kokonut.dev/

    11 Comments
    2024/11/18
    18:24 UTC

    0

    Goodbye useEffect? Running functions when the application starts

    I've just learned that you don't need a useEffect to run some logic when the application starts.

    Previously I would run some functions inside a useEffect with an empty dependency array so that they only run in the first render. But according to react.dev initializing the application is not an effect. Quoting from the docs:

    Not an Effect: Initializing the application

    Some logic should only run once when the application starts. You can put it outside your components:

    if (typeof window !== 'undefined') { // Check if we're running in the browser.
      checkAuthToken();
      loadDataFromLocalStorage();
    }
    
    function App() {
      // ...
    }

    This guarantees that such logic only runs once after the browser loads the page.

    That's it, that's all they say about it, which leaves me with a lot of doubts: Can I run async functions? Can I fetch data and use it to initialize a useState?

    I honestly don't understand, and the documentation is scarce, can anyone elaborate a little more? Thanks.

    18 Comments
    2024/11/18
    17:58 UTC

    12

    Which Framework to use

    Hello, i wanna build an e-commerce website, so im planing to use react/react native for the front end (and django for backend, mainly as an API), is react alone is good enough, or should i use something like Next or Remix, and Suhffle.dev for ui items

    for context, im an experienced backend dev, i want something without unnecesery hassle

    thx.

    50 Comments
    2024/11/18
    13:24 UTC

    0

    Easiest way to implement react table virtualization ?

    It seems like it’s not easy to implement it I tried react-window and the table displays as like a list .

    For react-virtual I got errors after errors and I’m not an expert .

    Thinking of react-virtualized but i think it is very difficult

    17 Comments
    2024/11/18
    12:51 UTC

    0

    Kickstart your Remix development with my stack!

    1 Comment
    2024/11/18
    11:44 UTC

    25

    Is using self made singletons or observer patterns an anti-pattern in react?

    I recently was working on a codebase that had a custom hook with a useState with a number value. The point of the hook was to add an event listener for when someone presses Ctrl+f and then +1 to the state and return this state.

    This custom hook started triggering errors after updating to newer react and nextjs version. Something was now causing the setState function to fire often enough to trigger the repeating calls setState failsafe.

    As it turns out a single component was using this custom hook, but there could be multiple instances of this component on one page, effectively meaning that the hook was being called from 30+ components upon clicking Ctrl+f.

    The first solution I tried to PoC that this was the issue was to reduce the number of instances of the custom hook. Initially I hoisted the hook to a high level parent component that was instanced a single time, then prop drill the state value. This solved the error message but resulted in an uncomfortable amount of props added to components to drill down.

    To alleviate this I decided I'd try to create a singleton by adding a variable to the global scope of the custom hook module:

    const stateInstance;

    function detectPageSearch(){ Code to add value to stateInstance and add event listener + logic. }

    Then add a listener function that simply returned the stateInstance.

    This worked, the parent component used the detectPageSearch function, the component that needed the value used only the listener function. The number of calls went down and there were no errors.

    The reason I'm bringing this up is that the team I'm working with was worried this is a react anti-pattern.

    So I'm wondering, is this seen as an anti-pattern? Does this break one of the tenets of react? Does using such global instancing break with something in react? I know you can use context, I've already described prop drilling, are these the ideal alternatives in a react codebase?

    Thank you.

    58 Comments
    2024/11/18
    10:56 UTC

    0

    React table some questions

    One i loaded more than 1000 rows With only 10 col Server side pagination

    I see how react turns snitchy I know pagination should not reach 1000 or more

    But in general I want to accelerate that snitching.

    8 Comments
    2024/11/18
    09:33 UTC

    17

    I Don't Fully Understand the Timing of useEffect Execution

    I want to wrap a chart component using Chart.js. I want the chart to only initialize once, rather than re-initializing every time the data is updated, to improve performance. However, I have a question: do I have to initialize the chart inside useLayoutEffect?

    I’ve seen some examples saying that using useEffect doesn't guarantee the canvas DOM will exist, and since initializing a Chart.js instance requires the canvas element, I’m concerned. But at the same time, I’m worried that using useLayoutEffect might negatively impact performance. Can anyone explain this? Is there something wrong with my approach?

    import { useRef, useEffect, useLayoutEffect } from "react";
    import Chart from "chart.js/auto";
    
    export default function ChartJS({ type, data, options }) {
      const canvasRef = useRef(null);
      const chartRef = useRef(null);
      useLayoutEffect(() => {
        chartRef.current = new Chart(canvasRef.current, { type, data, options });
        console.log("created chart");
        return () => {
          chartRef.current.destroy();
          console.log("destroy chart");
        };
      }, []);
      useEffect(() => {
        if (chartRef.current) {
          chartRef.current.config.data = data;
          chartRef.current.update();
          console.log("update data");
        }
      }, [data]);
      return <canvas ref={canvasRef}></canvas>;
    }
    
    
    16 Comments
    2024/11/18
    07:29 UTC

    16

    Recommendations for a library to sync query strings with state in React? 🙏

    1. State persists even after a page refresh.
    2. Updates to certain states automatically reflect in the URL query string (and vice versa).

    I’d prefer a solution that’s lightweight, easy to integrate, and well-maintained. Bonus points if it plays well with modern React features like hooks!

    Any recommendations or tips would be greatly appreciated. Thanks in advance!

    17 Comments
    2024/11/18
    01:01 UTC

    Back To Top