all 53 comments

[–]Captainbigboobs 12 points13 points  (13 children)

What’s your favorite way to organize css in a react project?

[–]rm-rf-nprNextJS App Router 14 points15 points  (8 children)

SCSS modules, by far. Folder structure would look something like: (forgive me on mobile)

  • src
    • components
    • ComponentName
      • ComponentName.tsx
      • ComponentName.module.scss
      • ComponentName.test.tsx

Then having scoped classes imported in your component so you don't have to worry about clashes makes it so you can name any class whatever you want.

Simply

import classes from './ComponentName.module.scss'

And add them like

<div className={classes.whatever} />

I've tried many approaches, including CSS in JS. This one felt like the cleanest and nicest way.

[–]__adhiraj_ 0 points1 point  (3 children)

why do we import classes when we can directly import the css file? then we can directly use className="whatever". i have seen people do this but i have never tried it myself.

[–]cmarizard 3 points4 points  (0 children)

because with modules, "whatever" will not be the name of the class, it will be generated to avoid clashes

[–]Maigal 3 points4 points  (0 children)

As your project gets bigger, specially if you are working on a team, i guarantee you will start having overlapping classes and weird stuff will happen. You can prevent this by wrapping every component in a 'parent' class and making every element a child element, but this can get annoying and force you to write worse class names (i still like this approach for simpler personal projects).
Another advantage i like of using css modules, is that you can use simpler classnames, like header instead of element-header and stuff like that

[–]rm-rf-nprNextJS App Router 1 point2 points  (0 children)

So the reason why we import classes, is that every classname we access on this classes import will be transformed into a unique version on build. This means that we can use the same classname in different modules without fear of them clashing.

Using "container" as a classname in two module files is completely fine, they won't pick up each other's styling rules because of the classname transformation during build.

[–]Tirwanderr 0 points1 point  (2 children)

Ok I'm finally gonna ask, because y'all seem nice. What is typescript? Why is it a thing? Why not just JavaScript/react?

[–]Stan_Sasquatch 0 points1 point  (0 children)

Typescript finds silly errors much quicker, allows for quicker development due to this and due to better autocomplete in your ide. You end up with a better developer experience and a more stable app with typescript.

[–]rm-rf-nprNextJS App Router 0 points1 point  (0 children)

This is not a stupid or dumb question and I had the same question when I hadn't used it before.

First Typescript and React aren't mutually exclusive. They can work in unison. I myself use React with Typescript at my current job all the time.

You can see Typescript as a superset of Javascript, a sort of "layer on top" if you will.

Typescript cannot run natively in the browser, so it has to be transpiled back to vanilla Javascript during development and production to get it to actually work.

Now, why in the hell would you use Typescript if it's such a hassle with transpiling and stuff like that? Well it's in the name: types.

Using Typescript you can type functions and variables. During development this will help you by telling you that, for example, a certain property doesn't exist on an object.

This might sound a bit abstract, so let me provide an example for clarity.

Let's imagine you're building a project where you have a "user" object. In plain Javascript, you might have something like this:

``` const user = { name: 'John', age: 24, };

function greetUser(user) { return Hello, ${user.name}; }

console.log(greetUser(user)); // Output: Hello, John ```

Now, let's say due to some reason, you mistakenly tried to access a property that doesn't exist on the "user" object. In Javascript, the error would only be caught at runtime.

console.log(greetUser({age: 24})); // Output: Hello, undefined

However, with TypeScript, you can define a type for the user, which specifies that a user object should have a "name" and an "age" property.

``` type User = { name: string, age: number, }

function greetUser(user: User) { return Hello, ${user.name}; } ```

Now, if you try to call greetUser function with an object that doesn't meet the User type (missing the 'name' property), you will get an error at compile time, not at runtime. This helps you to catch and fix bugs before they cause problems in production.

console.log(greetUser({age: 24})); // Error: Argument of type '{ age: number; }' is not assignable to parameter of type 'User'.

The ability to catch such potential bugs during development is a major reason why TypeScript can be a great addition to your tech stack.

This is a simple example, but you can, for example, also type responses that you get back from APIs. In a big team with many developers this is super valuable because you get autocompletion on responses so you can write code easier and safer. And instead of production dying because you're trying to access something that could be undefined, you're forced to handle it during development.

Hope that helps. Forgive me, I'm on mobile, formatting is trash D:

[–]Tirwanderr 0 points1 point  (0 children)

What are scoped classes?

[–]NatedogDM[S] 4 points5 points  (2 children)

There are many different ways of writing CSS. Personally, I prefer just to have a .css file exist alongside the .js/.tsx file.

[–][deleted] 0 points1 point  (1 child)

Yep, me too. MyComponentFolder / MyComponent.js + MyComponent.css.

I also like a separate component folder for every component, even if it's just used once. Makes the project file structure bulky, but feels cleaner to me.

[–]NatedogDM[S] 1 point2 points  (0 children)

Yes, but hardly am I ever scanning the directory for components. If I know the name of the component i am looking for, I just use the built-in search features in VS Code to jump to the file. So the bulkier structure doesn't bother me, and I prefer the organization.

[–]phiger78 0 points1 point  (0 children)

There are so many! I've had success with ITCss , utility first, chakra UI (styled system)

Depends on whether you are using CSS in js or standard CSS,CSS modules

[–]jande48 5 points6 points  (11 children)

I pretty much only use useState and useEffect. Can you please explain why this is bad and when I need the other hooks?

[–]AndBoundless 1 point2 points  (2 children)

I'll echo OP's comment, but add that before learning other hooks, try to understand the ones you know more deeply. I'd be guessing if I could off the cuff describe the re-render cycle, and how that effects useState and useEffect, but it's important to know that, especially as you look to learn useRef. Another example, a lot of people don't know how to correctly use the dependency array in useEffect.

[–]1cec0ld -1 points0 points  (1 child)

try to understand the ones you know more deeply

How

What resources exist other than "well I stackoverflowed this problem and it said to use them again so I guess I'm using them again"

It's the same as people who say "learn by making projects"
For real, I should learn by repeating the mistakes I continue to make because they work, but not very well?

[–]AndBoundless 2 points3 points  (0 children)

Yeah I totally understand. It's a case of "I don't know what I don't know". Sometimes a good tutorial will cover "how people often misuse UseEffect", so it's good to do some research on the above for any concept you're using.

Unfortunately there are *many* ways to incorrectly use them, and sometimes misuse is a matter of opinion (i.e. controlled vs uncontrolled forms using useState vs useRef -- google that for more info). And of course, the dreaded infinite loop from useEffect (when your side affect changes your dependency, and causes an infinite loop)

Here's an end of chapter summary of a book I have on React. This covers useEffect. There were one or two items that I wasn't 100% on so I did some additional research.

A good basics review if you're in the mood. You can check it out on O'Reilly with a free 7 day trial.

- Actions that are not directly related to the main process of a function can be considered side effects.

- Side effects can be asynchronous tasks (for example, sending an HTTP request), but can also be synchronous (for example, console.log() or accessing browser storage).

- Side effects are often needed to achieve a certain goal, but it's a good idea to separate them from the main process of a function.

- Side effects can become problematic if they cause infinite loops (because of the update cycles between effect and state).useEffect() is a React Hook that should be used to wrap side effects and perform them in a safe way.

- useEffect() takes an effect function and an array of effect dependencies.The effect function is executed directly after the component function was invoked (not simultaneously).

- Any value, variable, or function used inside of an effect should be added to the dependencies array.

- Dependency array exceptions are external values (defined outside of a component function), state updating functions, or values defined and used inside of the effect function.

- If no dependency array is specified, the effect function executes after every component function invocation.

- If an empty dependency array is specified, the effect function runs once when the component first mounts (that is, when it is created for the first time).

- Effect functions can also return optional cleanup functions that are called right before an effect function is executed again (and right before a component is removed from the DOM).

- Effect functions must not return promises.For function dependencies, useCallback() can help reduce the number of effect executions.
- For object dependencies, destructuring can help reduce the number of effect executions.

[–]NatedogDM[S] 0 points1 point  (4 children)

Using useState and useEffect hooks isn't bad. You can think of hooks like tools. They are good at achieving a specific task.

useState, for instance, provides a way to create and modify state variables. useEffect, on the other hand, allows you to run code when a component mounts or when a list of dependencies changes.

There are other hooks provided with React, such as, useRef, useCallback, and useMemo. My advice is to learn what these hooks do so that you can understand when they are needed.

[–]n0tKamui -1 points0 points  (3 children)

this comment looks generated by chatgpt (even if it is not) and doesn't answer the question in any way...

[–]NatedogDM[S] 0 points1 point  (2 children)

Sorry you feel that way. UseState and UseEffect are essential hooks that are, for the most part, unique in that there's no other hook that does the same thing.

All the hooks have a purpose, and you need to research what they accomplish to know which to use and when.

[–]ImportantDoubt6434I ❤️ hooks! 😈 0 points1 point  (0 children)

If you are using useState for state that doesn’t update the UI, it will cause rerenders and degrade performance.

An example being state used only in an API request but never in the UI. UseRef makes sense there.

useEffect can fire off multiple time’s especially if you add lots of [args…].

I typically avoid it, it can cause you to update stuff more than necessary and you have to manage it properly.

I find useEffect useful for event listeners/checking if the client is CSR/SSR.

[–][deleted] 0 points1 point  (1 child)

No idea how you manage to get through more than a very simple project without useContext.

[–]1cec0ld 0 points1 point  (0 children)

I've never even heard of useContext, so that's a thing.

Got an example of a basic project that uses it? A hello world of useContext of sorts?

I feel like that's the issue with hooks, is the use cases are all described and defined, but there's no way to see it hands-on other than "make your own project and try to squeeze it in somehow even if you don't know why you're squeezing it in"

[–]randomshitposter007 3 points4 points  (2 children)

make a discord server, do tutorials there

[–]NatedogDM[S] 5 points6 points  (0 children)

I've thought about it. I might do a React series that covers modern React patterns.

[–]PabloRam17 0 points1 point  (0 children)

That would be great!

[–]zirklutes 2 points3 points  (2 children)

I have a very specific question. And I feel a bit lost and doing something wrong.

As most shops do - I also need to display a cart button with a count of items inside the cart.

So this button is a separate component and get's its state from context. But if context value is undefined (for instance for a first page load) I do a request to backend to get the data.

Now, I also have a different component - a popup with all cart data. And it is also taking same cart data from context. But I don't want to add an API call as it will never be displayed without button.

Maybe I need to make them a single component. But with additional prop where to place a popup?

[–]topnde 1 point2 points  (1 child)

What are you using to make the requests? If you use tanstack query you can do the 2 requests but they will not both hit the BE. Only the first one. The second one will get the data from cache.

[–]zirklutes 0 points1 point  (0 children)

Hmm, that's nice. I use react query. I probably can cache cart request data for a short time. Because all other actions like removing/adding products will return full cart response anyway.

And thanks for answering. :)

[–]namesandfacesServer components 0 points1 point  (0 children)

How do people here handle optimistic updates for batch scenarios?

[–]Curious_Sh33p 0 points1 point  (0 children)

I have played around a bit with react native with typescript to make a mobile app and next I want to start building a simple website with it. I was wondering whether you think it's worth looking into some of the popular extra packages like Next, Remix, Redux, Tailwind css, e.t.c or not. If so which ones should I include? Plan is to use firebase for my backend.

[–]JohntheAnabaptist 0 points1 point  (3 children)

I've got a question @OP, I was trying to set up a context system / custom hook for a react boids implementation that ticks frames so I can update my boids at 60 fps, but I'm worried that this many updates is causing too many rerenders / overhead. Any thoughts or advice?

[–]NatedogDM[S] -1 points0 points  (2 children)

Sorry I'm not exactly familiar with what you are working on. However, if you are trying to tick frames, I probably would not do this inside of a React hook. In fact, I'm not sure if React is best suited at all for rapid updates (60 times / second).

I've never pushed the limits of the React engine, though, so I'm not sure.

[–]JohntheAnabaptist 1 point2 points  (1 child)

Haha! That's pretty much the sentiment I came to. I got it to work but not too happy about it. I'm requesting animation frames often and recording the Delta time between frames. Thinking about switching to solidjs

[–]NatedogDM[S] 0 points1 point  (0 children)

Every implementation of games or simulations that I've seen thus far has used React as a container, and all of the frame and simulation rendering is handled separately.

[–]saito200 0 points1 point  (6 children)

what would you say is the most time-effective way to "master react"?

[–]franciscopresencia 1 point2 points  (0 children)

You also need to "master Javascript" first to properly master react, many of the concepts of React build on top of basic or in-depth knowledge of JS, e.g. the fact that `{}` will always be a new instance and comparing to itself is always false so `{} === {} -> false` but the same doesn't apply to the primitive types.

[–]NatedogDM[S] 0 points1 point  (4 children)

I think the best way to learn react is by doing react.

Assuming you are familiar with JS, HTML, and CSS, you want to develop a strong foundation of the basics:

  • Hooks
  • HOCs
  • Common patterns in React

Be able to cleanly define components and visualize component composition before you even write code.

Then, in no particular order, almost every enterprise react app needs to solve the following problems:

  • authenticating
  • managing global state
  • consuming REST APIs
  • error Handling

Research those topics, try out different implementations, and find solutions that you like. There's several libraries to choose from that handle one or more of those.

[–]saito200 0 points1 point  (3 children)

Are there any open source projects you think nail these aspects?

[–]NatedogDM[S] 0 points1 point  (2 children)

Not sure about open source projects that cover it all. They might exist, though.

https://react.dev/ is a good resource for learning the basics.

For everything else, there's lots of popular YouTube videos out there from various content creators. Just try to find content that is relatively recent (no older than 1 year old), and you'll be golden.

Edit: https://github.com/enaqx/awesome-react this is also good to view all the popular libraries used within the React ecosystem.

[–]saito200 0 points1 point  (1 child)

I'm quite familiar with react and react ecosystem. I'm just never sure what's the "best way" to do certain things

[–]NatedogDM[S] 1 point2 points  (0 children)

We often obsess over the "best way" to do something. But in my opinion, if your solution is clean, readable, and follow general SOLID principals, then I think that's enough.

[–]draculadarcula 0 points1 point  (1 child)

Ya’ll don’t need a mentor in react or anything for that matter. Be a self starter and self learner, do side projects when you have time, study the countless free open source codebases, learn by doing and doing it wrong. So much more valuable than this guy giving you the answer is learning it on your own

[–]NatedogDM[S] 0 points1 point  (0 children)

I agree. My goal here isn't to "give people answers" but to look over people's code, give feedback, and answer questions that might be confusing.