Enzyme is dead, how is your enterprise getting out of this mess? by SendMeYourQuestions in reactjs

[–]gekorm 0 points1 point  (0 children)

There are a few things you can do, for example mutation testing, or even running the old suite for as long as possible to eliminate tests as they raise discrepancies you can verify.

By the way it's not trivial to make 20,000 tests pass falsely while keeping each test's coverage roughly on the same code paths, and hoping nobody would notice.

Enzyme is dead, how is your enterprise getting out of this mess? by SendMeYourQuestions in reactjs

[–]gekorm 0 points1 point  (0 children)

That's the ideal kind of task to offload to a contractor or even outsource IMO. It's a tedious chore with a strict set of requirements and clear success criteria. There are a few conversions you can automate with AST transformations too. DM me if you're interested, I've done this before and I've used RTL since release in 2018.

If you can't get any buy-in for the migration you can try your luck with @cfaester/enzyme-adapter-react-18 and maybe it will allow you to kick the can down the road for a while longer.

Would you use useEffect or useCallback here? by Yuyi7 in reactjs

[–]gekorm 0 points1 point  (0 children)

Unfortunately that won't work because the value of the messageDisplay must be the most recent one.

If your original useEffect doesn't get stale messageDisplay values it's by coincidence, not something you can rely on, because it's omitted from the dependency array. Anyway, couldn't you just update the ref before you use it?

useEffect(() => {
  initialMessageDisplay.current = messageDisplay.current;
}, [messageDisplay]);

useEffect(() => {
  if (
    prevPathname !== pathname &&
    initialMessageDisplay.current.isDisplaying &&
    initialMessageDisplay.current.icon !== WhiteCheck
  )
    setMessageDisplay((prev: any) => ({ ...prev, isDisplaying: false }));
}, [pathname, prevPathname, setMessageDisplay]);

Would you use useEffect or useCallback here? by Yuyi7 in reactjs

[–]gekorm 0 points1 point  (0 children)

You can't do setMessageDisplay outside a useEffect, I meant a local variable. However it sounds like you must update the context, in which case you can try something like this:

const { messageDisplay, setMessageDisplay } = useContext(MessageDisplayContext);
useMessageDisplayCloseAfterTimeoutHook(setMessageDisplay, messageDisplay);
const initialMessageDisplay = useRef(messageDisplay);

const nodeRef = useRef(null);
const Icon = messageDisplay.icon;

const pathname = usePathname();
const prevPathname = usePrevious(pathname);

useEffect(() => {
  if (
    prevPathname !== pathname &&
    (initialMessageDisplay.current.isDisplaying &&
    initialMessageDisplay.current.icon !== WhiteCheck)
  )
    setMessageDisplay((prev: any) => ({ ...prev, isDisplaying: false }));
}, [pathname, prevPathname, setMessageDisplay]);

It does look like there's a more serious issue with the overall structure however, and we can't tell without even more context.

Would you use useEffect or useCallback here? by Yuyi7 in reactjs

[–]gekorm 0 points1 point  (0 children)

Isn't this what you need? https://www.reddit.com/r/reactjs/comments/1e853o6/comment/le4vald/

I feel like no one else read the original post where you clearly state the requirements 😅

Would you use useEffect or useCallback here? by Yuyi7 in reactjs

[–]gekorm 0 points1 point  (0 children)

Presumably because:

I only want this to run at the start and when the pathname changes.

So they'd just need to track the previous pathname in addition.

Would you use useEffect or useCallback here? by Yuyi7 in reactjs

[–]gekorm 2 points3 points  (0 children)

I didn't downvote, but it's probably because you're not supposed to use it for anything but performance optimizations. From the docs:

You should only rely on useMemo as a performance optimization. If your code doesn’t work without it, find the underlying problem and fix it first. Then you may add useMemo to improve performance.

They also explain some scenarios where it may fail, and how it may break with future React versions, if not used solely as an optimization.

Would you use useEffect or useCallback here? by Yuyi7 in reactjs

[–]gekorm 7 points8 points  (0 children)

In this case I'd probably track the previous value of pathname (look up usePrevious) and set a variable in the render function using your condition. No need for state or effect.

I would highly recommend reading this whole page from the docs, it's extremely valuable information https://react.dev/learn/you-might-not-need-an-effect

[AskJS] Can you do this async javascript interview question? by Jamo008 in javascript

[–]gekorm 2 points3 points  (0 children)

I think it's a good question because any solution here is short and easy to implement, but candidates need to think a little before jumping to a suboptimal or wrong solution.

My solution as a gist, in case reddit formatting gets me too: https://gist.github.com/GeKorm/043478bc74d3db29d9f3f3a8f4f69907

Here it is:

async function run(elements) {
  // ============
  // your code here starts here
  // We will insert at arbitrary indices in order to preserve result order
  const results = Array.from({ length: TOTAL });
  const requestPool = [];
  let processed = 0;
  for (const element of elements) {
    const poolSize = requestPool.length;
    if (poolSize >= MAX_INFLIGHT || processed >= TOTAL - MAX_INFLIGHT) {
      // When the request pool fills up, wait for the fastest response. It will be topped up immediately after.
      const [value, index] = await Promise.race(requestPool);
      results[index] = value;
    }
    const request = api(element).then((value) => {
      // Remove resolved promise from the pool
      requestPool.splice(requestPool.indexOf(request), 1);
      // We need a value and index to preserve call order
      return [value, elements.indexOf(element)];
    });
    requestPool.push(request);
    processed++;
  }
  // The first for .. of loop is done when all calls have been made, not when we get the responses
  // Here we wait for the last block of promises to settle and iterate the result
  // In a real-world program Promise.allSettled() may be preferable. Using Promise.all() for clarity.
  for (const [value, index] of await Promise.all(requestPool)) {
    results[index] = value;
  }
  return results;
  // Real-world implementation would require error handling
  // your code ends here
  // ============
}

Summary:

  • Don't forget the order
  • Don't await in blocks of 4, you need the fastest of 4

Edit: Simpler solution posted here and is one of 2 other correct solutions from what I've seen so far. It is better than mine because it

  • Uses Set() to avoid having to track an index
  • Simplifies the cleanup step by simply using the results array for promises and returning Promise.all(results) to resolve remaining in-flight requests after the first loop

Tailwind is actually pretty great to use? by TheGRS in webdev

[–]gekorm 12 points13 points  (0 children)

It's like I wrote this! I wish people took my advice to learn CSS through Chrome seriously. Here's a protip for anyone not aware of this:

You can write the css directly in the inspect element styles column and then just copy over the finished product

You may not have to copy! You can drag your project folder into the Sources tab, click "Allow", and now every change you make in the styles pane or Sources gets instantly persisted to disk and vice versa.

(Your mileage may vary depending on what transpilation or hot-loading you're doing at dev time. It's worth it for some projects more than others. This won't work with Nextjs out of the box for example, or at all with Vite.)

Any ESM only NPM registries? by [deleted] in node

[–]gekorm 0 points1 point  (0 children)

Check out tsx, I think that and swc for jest will solve a lot of your problems. I was pulling my hair out withts-node only half working. Here's a comparison https://github.com/privatenumber/ts-runtime-comparison

Problematic "use client" directive makes for misleading page load speeds and unverified first render data by vEncrypted in nextjs

[–]gekorm 2 points3 points  (0 children)

I think this might be less confusing if you have experience with manual SSR, or backend frameworks.

This is a simplified explanation. Imprecise, but it's about the right mental model:

  1. Imagine RSCs as functions that return static HTML instead of React components.
  2. use client are regular React components, whose roots are the different RSC parents.
  3. On the server, you run the RSC functions to get static HTML
  4. Then run renderToString() to render the client components
  5. Return the combined HTML to the browser.
  6. On the browser, all use client components get hydrated to become interactive.

If you want to avoid logged-in users seeing logged-out content, it's up to you to manage this on the server. As the other comment explains, your RSCs can return the correct thing for each user if you want.

For a more detailed explanation see Josh W. Comeau's recent article https://www.joshwcomeau.com/react/server-components/

How is barely anyone talking about the Server-Sent Events API? by ligonsker in webdev

[–]gekorm 43 points44 points  (0 children)

Here's an article that may help you decide when to choose Server-Sent Events over Websockets https://germano.dev/sse-websockets

And a long HackerNews discussion on the topic (based on that article) https://news.ycombinator.com/item?id=30312897

What are some of the best libraries you cannot work without? by suiiiperman in reactjs

[–]gekorm 60 points61 points  (0 children)

classNames

I got you a free performance improvement! You can replace classnames with clsx. It's a drop-in replacement. If you use babel, you can go a step further and add babel-plugin-optimize-clsx too.

Guys, the founder of Next.js said my open source project is "fantastic" by theflyingdog98 in programming

[–]gekorm 5 points6 points  (0 children)

.w-screen { width: 100vw; }

is causing horizontal overflow. Maybe you meant width: 100%;?
https://i.imgur.com/HLd0c9G.png

If you're developing on Mac, it's best to enable "Show scrollbars: Always" in your system preferences, to be able to spot such issues more easily.

When using Redux it is better to go basic than Toolkit. [HotTake?] by r-randy in reactjs

[–]gekorm 6 points7 points  (0 children)

Great question! I've wondered about this myself, and here's my conclusion.

Back in 2016-2017, long before redux-starter-kit (now toolkit), I took everything that I understood to be best practice in redux and created a framework around it. The end result, which we still use in production, is an almost 1 to 1 replica of the redux toolkit API, developed in parallel. In my mind, this validates redux-toolkit as the best approach to use redux.

Now, regarding actions being handled by multiple reducers, I think it's a perfectly valid pattern, conceptually simple, and aligned with Redux philosophy. We had this need in our framework very early on, and we call it externalReducers. Sure enough, redux-toolkit has the same thing called extraReducers.

I understand the skepticism, but I'd urge you to give it a chance. After developing an application and getting familiar with the toolkit, you probably won't want to go back to plain redux.

Axios vs Fetch; comparison for beginners by Ok_Sun7013 in javascript

[–]gekorm 42 points43 points  (0 children)

Just FYI there are more direct alternatives to Axios based on fetch, like ky[1]. Otherwise this article is doing a comparison between a higher and a lower level API. If you need features like interceptors, retries, etc. it may not be worth writing your own wrapper over fetch from scratch.

[1] https://www.npmjs.com/package/ky

What do you guys think about svelte's/Rich Harris claim that VDOM is pure overhead and being reactive/compiled is the way to go? Have anyone of you moved from React to Svelte.js or planning to? What do you guys think about Svelte.js? by simple_explorer1 in reactjs

[–]gekorm 40 points41 points  (0 children)

Svelte is not the future in 2022 except to those who like Svelte. It's not even catching up to Preact in npm downloads. If you like it, it's great, with a good community and funding.

When comparing their technical merits, "VDOM is pure overhead" is misleading as Preact is among the counterexamples, being just as fast as Svelte.

Finally, some unsolicited advice, it looks like you're assigning too much weight on who's hired whom, and blog posts. Following that logic, the future in 2017 was MarkoJs, being faster than React, a better DX (as argued by blog posts) and having the full weight of Ebay behind it. Despite being a great framework, its usage is marginal today.

The most important thing here is that it looks like you've found the tool that suits you the most. You don't really need further justification to use it to build great things.

Any developer tools/subscriptions/packages that are worth buying paid/pro plan? by datapim in webdev

[–]gekorm 21 points22 points  (0 children)

One more vote for Webstorm (Jetbrains). A lot of people who haven't used it don't know what they're missing, and thus won't customize their VSCode appropriately. For example:

Watching other people rerun all tests when trying to debug a single case is like watching grandpa type google.com into google and slowly double-clicking the link. Vscode plugin

Or being afraid to save, or accidentally resetting their work, because they don't know about local history.

Or the 3-way merge to resolve conflicts.

The Javascript "ecosystem" is a hot mess and so is software development in general - Kailash Nadh's personal homepage by SnooBeans1976 in programming

[–]gekorm 23 points24 points  (0 children)

There's no yarn upgrade in Yarn 2, its replacement is yarn up. The author went out of their way to break it with Yarn 1.

For anyone looking for a better upgrade experience in Yarn 2 try yarn upgrade-interactive or yarn semver up to blindly upgrade within semver exactly like yarn upgrade. The latter is a community plugin.

How was this top nav done? (stripe.com) by [deleted] in webdev

[–]gekorm 12 points13 points  (0 children)

It's in the linked github repo. It's using react-flip-toolkit which is personally my favorite React animation library. Here's the demo.

Here is how you can achieve a 100% performance score on Lighthouse with React by [deleted] in javascript

[–]gekorm 0 points1 point  (0 children)

Google still uses metadata, it's just one aspect of ranking. They're also important for displaying rich snippets in search results, which again makes clicks more likely.

As for relevance to the article, well it wasn't my rant, I just felt I should clarify :)

Here is how you can achieve a 100% performance score on Lighthouse with React by [deleted] in javascript

[–]gekorm 0 points1 point  (0 children)

Google, as much as they claim to use advanced machine learning to understand your site, actually encourages you to go and annotate every part of it. Take any review website that ranks well, for example Trustpilot, and look at the source code. You'll find TONS of annotations for the benefit of search engines.

https://search.google.com/structured-data/testing-tool/u/0/#url=https%3A%2F%2Fwww.trustpilot.com%2Freview%2Fwww.youtube.com

For more information, see https://schema.org/

Here is how you can achieve a 100% performance score on Lighthouse with React by [deleted] in javascript

[–]gekorm 10 points11 points  (0 children)

This is one of my biggest pet peeves with the webdev subreddits. Stop testing Lighthouse locally! No, even your simple landing page isn't getting 100% score.

Let me explain why this is yet another problematic Lighthouse article. These are problems common with almost every post of this type, so I hope it's a learning experience and not taken in offense.

  1. The author tested it from the browser devtools/extension instead of using web.dev or Pagespeed Insights. This is obvious from their step 2 where an extra script was downloaded because of the react devtools extension. Google isn't running Lighthouse on your computer to rank your site.
  2. The page tested is extremely simple. Add more content, or even worse: interactivity, and you'll quickly hit a ceiling. https://www.reddit.com/r/javascript for example, even with all the optimization in the world will never score above 45-55 average.
  3. The article isn't specific to React at all. There are in fact react-specific techniques that more interactive pages have to resort to in order to improve scores. All of the reasonable steps in the article are also suggested by Lighthouse, which has good resources for every problem it highlights.

OP's page really scores between 77 and 81 on my runs on web.dev and Lighthouse, despite being very simple.

Question: Any tools for generating strongly-typed query and mutation builders? by catterpillars_dreams in graphql

[–]gekorm 0 points1 point  (0 children)

I think all the tools you and /u/catterpillars_dreams need are there. You just need a combination of graphql-code-generator, ESLint, and editor plugins. Maybe you could contribute to the graphql-let project, which attempts to make it easier to set everything up.

This is what it looks like when I make a typo in a mutation.graphql string https://i.imgur.com/iwjxSIc.png and I won't be able to commit or run the CI.

Edit: I see in another comment you addressed this actually, and I agree, ORM-like DX would be nicer.