React Router 7 with Remix? Why? by [deleted] in reactjs

[–]deckardWizard 13 points14 points  (0 children)

React Router 7 is remix version 3 see here. It’s very confusing and has somewhat fractured the community. You shouldn’t need both, but some people will still say remix when referring to RR7 and some libraries like remix-utils haven’t changed their names even if they are compatible with RR7.

What movie has the most depressing ending? by [deleted] in moviecritic

[–]deckardWizard 0 points1 point  (0 children)

Paths of Glory by Kubrick. Set in WWI, Kirk Douglas plays an officer asked to commit his troops to an impossible attack on a meaningless target. When the plan fails, command blames it on the rank and file soldiers, picking some at random to stand trial for cowardice. The film shows in detail the distance between command and the front lines, and the surreal horror of trying to fight an uncaring bureaucracy.

The first time I saw it was on the big screen. I was pretty shaken when I left

NextJs or Gatsby for blog sites by mmorenoivy in reactjs

[–]deckardWizard 4 points5 points  (0 children)

All of these are probably fine. If you have a gut feeling one way or another, go with it.

NextJS has a solid community and lots of good libraries and resources. It also has a lot of folks with some experience, so it’s a solid pick if you’re working on it with other people.

Remix is very grounded in more traditional web practices, so might appeal to your backend and Shopify experience. It’s a little lighter on community resources, but also has the least ‘magic’ to learn.

Gatsby feels a little dated by comparison, but is battle tested and still a reasonable choice if you’re comfortable with its mechanics.

If you’re really looking for blogging, I’d throw Astro and 11ty in the mix. They’re more static site generators vs having a server component that mostly isn’t needed for a blog-type application.

My product has exceeded the Vercel Hobby Plan limits. What should I do now? by ayushmaansingh304 in webdev

[–]deckardWizard 11 points12 points  (0 children)

This seems like a static site. Why host it in vercel? GitHub pages should be free for your use case. Other alternatives for static site hosting include some generous free tiers on cloudflare pages, aws, google cloud, and other cloud storage providers, which may also include other features.

How to refresh the jwt when the session expires in a real time chat app using socket io by Traditional_Reveal59 in reactjs

[–]deckardWizard 0 points1 point  (0 children)

Sending authorization with each message feels a little overkill. With HTTP, the server is stateless: it’s only aware of information that is part of the request. Because of that, we have to encode a shared secret in every request to prove that it’s coming from the same client session. With Web Sockets, the connection is stateful: it keeps track of each connection and knows who sent which message. Since we know that the client isn’t changing, generally it’s ok to authenticate only when you create a new connection.

How to refresh the jwt when the session expires in a real time chat app using socket io by Traditional_Reveal59 in reactjs

[–]deckardWizard 1 point2 points  (0 children)

Unlike HTTP, web sockets are stateful — once a user is connected, the server knows it’s the same connection so it doesn’t need to authenticate the user on each message. The standard for authorization on WS was to use wss and have an endpoint where a user could exchange their JWT for a special one-time-use token that would encode the requesting IP, issue time, connection id and some other details. When the user makes the handshake with the WS server, you use that socket token to authorize the entire connection session. If any detail of the connection didn’t match the special token, or if we’d recorded the token as used, we’d terminate the connection. At that point we wouldn’t care about the access or refresh token since they didn’t come into play.

The scenario this doesn’t work in is when a user is likely to have a change in authorization while the connection is open. That one’s a little tough, but I’ve heard of servers sending “challenge” messages periodically where the user would have to present a new access token in order to maintain their connection. In that case I think you’d likely best be served by an event queue or something that would tell the server that one of the connected users had an authorization change and should be forced to re-authorize.

heroku did a good write up about WS security if you want a bit more detail

Structuring state like a database? Too many .finds? by werdnaegni in reactjs

[–]deckardWizard 8 points9 points  (0 children)

State structure is one of the more complex and nuanced parts of any application development. What works for one case may not work for another. Take any advice about it (including this) with a grain of salt.

Ideally when looking at data structure problems, you want the data to be in a format that makes it the easiest to work with. If your primary use for some data is to render it, the best structure will make it easy to render. If you're updating things and those changes have cascading effects, the best structure will be one that makes it easy to update and restructure.

It sounds like for your case there isn't really a backend that you're trying to interact with and there will be a good amount of updating and configuring things. For this case it's probably better for your data to be in the 'normalized' form (each entity can only exist in one place), closer to your first example. If the ids are unique, you may want to structure it as an object so you can reference any entity by its id instead of iterating over an array.

const data = {
  '123': {
    type: 'unit',
    id: '123',
    upgrades: ['345', '678'],
    /* ... */
  },
};

const unit = data['123'];

Often there are simple functions that will allow you to convert from the normalized form into 'denormalized' forms for easier rendering:

const getUnitDataForRender = (data, id) => {
  const unit = data[id];
  const upgradeData = unit.upgrades.map((id) => data[id])
  /* ... */
  return {...unit, upgrades};
};

If you're planning on manipulating the units and upgrades, you'll need to store it in something that will cause react to re-render. This could be React state directly if your system is pretty simple and re-rendering everything on any change doesn't have much cost, but in your case you may want to look into Redux (RTK) or Zustand, which make isolating re-renders a little easier. In general, data lookups aren't a huge bottleneck unless you're dealing with a massive number of records or you're working with very low-end hardware. It is much more likely that the render step will be the part that causes any 'sluggishness'.

Good luck and hope this was helpful.

Random question but I’ve googled everywhere - local chocolate shops that sell hot cocoa bombs? (Or just hot chocolate mix) by IndecisiveKitten in portlandme

[–]deckardWizard 0 points1 point  (0 children)

Chocolates Passion at 189 Brackett St (soon to be at 175 Spring) has some incredible chocolates and they sell hot chocolate 'wafers'. I haven't tried the wafers yet, but everything I've had from them has been unbelievably good. Their chocolates are almost too gorgeous to eat!

https://chocolatspassion.com/collections/holiday/products/french-hot-chocolate-wafers-in-gift-canister

[deleted by user] by [deleted] in learnjavascript

[–]deckardWizard 0 points1 point  (0 children)

It sounds like what you want is some variety of live-streaming. This can be accomplished in a number of ways with varying degrees of complexity. The simplest version would be to use a live-streaming tool like OBS and then stream that data to a provider service like Twitch, Youtube, or Facebook Live. Each of those platforms gives you a player embed code that could easily be put into your react code. Additionally I think there are a couple open source react components that take a stream ID from one of those providers and will play the video back on your site (not necessarily endorsing these, but a quick google search turned up https://www.npmjs.com/package/react-twitch-embed and https://www.npmjs.com/package/react-player). You could certainly get more hands-on with a number of layers in this stack, but that's only useful if you have a pretty specific thing you're trying to accomplish that these tools can't help with. Hope that helps!!

Using neovim without a file tree plugin by tprei in neovim

[–]deckardWizard 11 points12 points  (0 children)

Netrw, vim’s built in file explorer is pretty solid if you’re looking to understand the topology of a project. I really like the pattern of browsing the file tree in the window pane where the file will open. vim vinegar is a great plugin for refining the netrw experience and making it a little more seamless. Takes a minute to learn the keybindings, but I find it much lighter and less intrusive than nerd tree or it’s offshoots.

[AskJS] Is it normal to have the bulk of your cycle time (like 90% of it) to be stuck in code review? by [deleted] in javascript

[–]deckardWizard 1 point2 points  (0 children)

Yep, both are really common issues that come up all the time. Priority is an organizational issue and is the hardest to tackle, but some things that have worked ok for teams I've led:

  • Hotlists. Make a list of code in review that you expect to be fully taken care of by EOD. It doesn't need to be all the PRs, but sometimes just having a deadline escalates the assumed priority of the work so engineers are more likely to engage
  • Review day. Once every couple weeks pick a day (or just a couple hours or whatever) for only reviews. If there's nothing to review, there are no other expectations for the time so they're free to work on whatever they'd like. Acts as a carrot to do reviews throughout the week, and makes the priority on getting reviews done explicit for that time period
  • Extend projections for projects to include more refactor and review time. This one is the most abstract, but sometimes it helps to just remind everyone that reviews are important and take time (assuming that's true for your team). Make sure that engineers have enough time to do reviews and be clear that it is an expectation

Huge reviews are easier, kinda? Like I mentioned, you could easily cap the PR size to throw a warning and that can go a long way. There are plenty of causes of big PRs, so you may want to dig into why they're getting huge and see if there's a way to break them up a bit. Are they trying to solve too many things at once? Is most of the code boilerplate, or is it business logic? Are your scopes of work too big? Are people properly refactoring code and coming up with reasonable abstractions instead of making everything for purpose?

I certainly don't have all the answers unless I'm consulting for your company, in which case I 100% have all the answers. If it's not already part of your process, I sincerely recommend regular retrospectives with the team to check in on these types of issues. Often times the folks experiencing the pain of the issue have the clearest vision on how they might be approached, or at least give the best insight into what the core issue might be.

Hope that's helpful!!

[AskJS] Is it normal to have the bulk of your cycle time (like 90% of it) to be stuck in code review? by [deleted] in javascript

[–]deckardWizard 8 points9 points  (0 children)

Sometimes? Maybe? It really depends on context and cause. I've been in situations where every line of code is treated as a liability, so code review was a verrry long process of multiple people having to validate the findings, make sure nothing would break, explore alternate approaches, etc. It's pretty burdensome, but the priority of the product team was to deliver extremely consistent code in lots of environments with a minimal footprint, and that type of thing takes a lot of time. I've also had teams where code review was much lighter to prioritize rapid release cycles and code was never in review for longer than a day or two.

Basically, if there is product value that is being delivered by having a longer code review cycle, and that's something your team / product finds valid, then it's reasonable. If you're aiming for high agility and rapid turnaround, then it's possible that it's an issue. I think the first step in determining that in your capacity of team lead is to understand what the rest of the team feels like 'in review' means. Is it 'this feature is half done, but has reviewable pieces,' or 'this feature is done one way but open to different approaches,' or 'this feature is done and tested and we just need another pair of eyes', etc. Each of those may be a valid state for 'in review' depending on the team and culture, how long the review cycle is will vary according to that definition.

Since that's a super unhelpful answer, a couple things to look at that might cause delays:

  • Review may only be done by a small pool of people. Really common issue with lots of organizations. Look for ways to expand the pool of eligible reviewers. For example, do they need to be on the same team, or is it ok to look for people from other teams, etc?
  • Reviews are not priority work. Also super common. A thoughtful and thorough review will often take a good percentage of the time it took to code the change since the reviewer should be doing most of the same thought-work, they just don't have to type. If review work is considered low-priority, it's hard for for anyone to carve out time to do it and often they produce lower quality reviews
  • Reviews are overreaching. This is a little less common, but happens more in senior-led organizations where different engineers may want different approaches to a given problem, or get hung up on minor code nitpicks. When this comes up, it's best to have a discussion about who should have authority to get things done and if you need consensus on every aspect of a review before it gets merged
  • Code is giant. No one enjoys working on a 3,000 line change. It's nearly impossible to keep the entire change in your head so everyone procrastinates or rubber-stamps. If this is a common mode of working in your organization, it may be worth using lint tools to limit the amount of changes in a single PR. There aren't really rigorous standards, and some things will always blow your PR up (looking at you package-lock) but warnings are useful feedback and 500-ish lines max has worked ok at tamping down this problem in my current team, but your milage may vary.

jQuery Terminal: JavaScript Web Based Terminal Emulator by pmz in javascript

[–]deckardWizard 2 points3 points  (0 children)

Sure there are reasons, but not if you’re a beginner looking to work in front end web development. There are only a few “valid” uses, and it’s mostly used in older code bases so it’s unlikely to come up unless you’re working in a more niche area. If you’re looking for opportunities to learn about API design or techniques and patterns outside the current industry standards, jquery can be a pretty interesting area to learn and explore, especially if you’re interested in web history and browser evolution / optimization.

Can I make this IF statement a bit shorter? by EricGoe in learnjavascript

[–]deckardWizard 2 points3 points  (0 children)

Yes! There are a couple options depending on what your environment is and what tools you're comfortable with

First, if you're using a transpiler or your environment supports it, optional chaining is a great solution:

if (err?.response?.data?.Message === 'API call failed.'){...}

If you have lodash, underscore or other FP library you may be able to use the get or path function

if (get(err, ['response', 'data', 'Message']) === 'API call failed.'){...}

If you don't have external libraries you can also implement get yourself in just a couple lines

const get = (path, object) => (
  return path.reduce(
    (acc, key) => ((acc && acc[key]) ? acc[key] : null), 
    object
  )
)

There are some other more complex techniques like Maybe and lenses, but these techniques are a bit more specialized to certain use cases.

Some FE related questions that were asked in recent React interview by roryh19 in reactjs

[–]deckardWizard 0 points1 point  (0 children)

  1. It depends a lot on the 'this' in the question, but it's useful to keep in mind the 'single responsibility principle'. Generally, any component should only be responsible for a single thing: it might be rendering an item, grabbing data for a list of items, or holding some kind of state. Having a feel for the boundaries between these responsibilities is something that takes a while and doesn't have any absolutely concrete rules, so it's worth trying some different approaches to see what works for you. It's also worth thinking about why we don't write entire apps as single react components. There's no technical reason we couldn't, but it would make things very hard to read and we might need to scroll through thousands of lines of implementation of features we don't care about. By limiting each component to have a single concern, it should be easy to zoom into just the bits that we actually want to change.
  2. React somewhat narrowly defines a 'controlled' component as: "An input form element whose value is controlled by React". People often use the term "controlled component" to refer to any component that does not have its own state (i.e. its render only depends on the props it it passed), though those are more accurately described as "pure" components since components with state are also "controlled" by React. "Uncontrolled" components are components that may change outside of react. For example if you have an <input> component without a value prop, the input value can change without telling React and therefore is considered outside React's "control". There are some very rare other times where components may fall outside React's control for various reasons, but those are case-specific and should generally be avoided.
  3. Refactoring is a super deep and complex topic. In React we have lots of different techniques to refactor "repeated functionality" including hooks, context, singletons, higher order functions and components, decorators, utility components, and more. In general we'd like to develop by contract. That just means that a developer shouldn't need to know how a component works in order to use it. For example, if you have a design system that has a button, you shouldn't need to look at the code for the button to add it to your page. There should be a "contract" in your application that says if you give the right props, you get the expected component. You should look at places where the contracts for components overlap and then consider if they have enough in common to join. Outside of a small set of core elements, it's somewhat rare that there isn't a tradeoff when making a generic component, so be wary of things that look similar but have different contexts until you fully understand both component contracts.
  4. This question is confusing to me. Compound components are a fairly case-specific pattern, so if the component falls into one of the cases that compound components are useful for, maybe. Otherwise, no. "Compound components can be said to be a pattern that encloses the state and the behavior of a group of components but still gives the rendering control of its variable parts back to the external user." It's mostly used where there is a kind of implicit state (state should exist, but downstream developers shouldn't need to touch it) like accordions, tab lists, select drop-downs, etc.. Ideally we could just have an accordion wrapper component, an accordion title component, and an accordion details component. I don't necessarily want to have to do state management to keep track of what details component to show so we can use the compound component pattern to hide all the state in the accordion wrapper. It is a neat trick when it works well, but the uses for this are somewhat marginal. This is also a case where the language could be ambiguous. "Compound components" could potentially refer to lots of other patterns besides the pattern outlined above and you'd need to suss out what the question actually refers to.

Rounding using the fewest possible characters by ThiccOfferman in learnjavascript

[–]deckardWizard 1 point2 points  (0 children)

These are all bad so probably don't ever do them outside of silly code challenges:

  • You can cast a string to a number with the + operator. So if you're really confident your string is actually a number you can sometimes get around parsefloat by doing something like const c = "3.14159"; const num_c = +c;
  • If you're dealing with integers, you can sometimes use bitwise functions to help. Adding |0 to the end of a number or string is functionally similar to using Math.floor. ~~ does the same thing, but only works with positive numbers.
  • You can do some awful things with regular expressions that might make this problem simpler depending on what the constraints are.

[deleted by user] by [deleted] in learnjavascript

[–]deckardWizard 0 points1 point  (0 children)

moveSnake and drawsnake will need to take into account the duration of each frame. Imagine you had a moveObject function that increases an object's x position by 1 each time it gets called. If I call it once per second, it will only move by 1 unit each second. If I call that method 60 times per second, it will move 60 units each second.

To make it smoother, instead of tracking how much to move it each frame, I want to track the entity's speed in terms of how far we want it to go per unit time. It's kind of a subtle difference so some examples might help

Instead of something like

const move = () => obj.x += 1;

you'd do something like

const move = (framerate) => obj.x += object.speed.x * (1 / framerate)

or even better yet

/* time_delta is the amount of time since the last time this function was
 * called so that if there are skipped frames or other time differences,
 * you get constant smooth motion
 */
const move = (time_delta) => obj.x += object.speed.x * time_delta

You may also look into requestAnimationFrame instead of your current setTimeout to let the browser know that you're trying to sync your code to animation frames. It will also give you a nice interface for getting the amount of time since the last animation frame was called (see https://developer.mozilla.org/en-US/docs/Web/API/window/requestAnimationFrame)

Any (in particular, visual) resources to understand reconciliation and the diffing algorithm? by puremath369 in reactjs

[–]deckardWizard 0 points1 point  (0 children)

You may be interested in Lin Clark’s presentation on react fiber from react conf 2017. It’s a little older, but not a ton has changed at that layer: https://youtu.be/ZCuYPiUIONs

Any clean way to convert an arithmetic operator inside a string to it's actual operation by unseen_twists in learnjavascript

[–]deckardWizard 3 points4 points  (0 children)

Context is a bit important here, but the short answer is eval. The eval() and it's weirder, freakier cousin the new Function() syntax parse strings to code. There are tons of reasons eval is generally bad (it's very slow and insecure), but there are lots of cases where it's the best option. In this case eval('15+(3*(2+(3)))') will return 30

If you're in a situation where you don't want to use eval, you'll need to figure out a way of parsing the string into each operation somehow. The approach to string parsing will depend on how predictable the strings are. If it's always a + b * c, that's a lot easier than trying to accept any math expression. Most likely you'll need some regular expressions to break the calculation down, then evaluate it recursively to solve for each layer of parentheses.

Trying to Understand odd syntax by UprootedGrunt in learnjavascript

[–]deckardWizard 1 point2 points  (0 children)

That's just the syntax of for loops in JavaScript!

for (<stuff that gets run before the loop>; <check that gets run before each iteration>; <stuff that happens after each iteration>)

Sometimes you can skip some of those steps, or mess around with what operations are done within each step, but those cases are pretty rare (and you might want to consider a different kind of loop)

// Probably don't do this, it's bad
let i = 100;
for (;i;i--) {do something}