Live data from Hacker News

Show HN: Tired of logic in useEffect, I built a class-based React state manager

thales.me

11–20 of 57 posts

Re: Show HN: Tired of logic in useEffect, I built a class-based React state manager

#11
post #3

All the examples are fetching data from a server, and in such cases I think tanstack query already does all the hard part. I feel like people under-use react query and put too much state in their FE. This might be relevant if your app has some really complicated interactions, but for most apps they should really be a function of server , not client, state. Of course this exact reasoning is why I moved off react altog…

It's not just react query, you can make a quick useFetch and useMutation hooks (or claude can), it's not that complex. If you don't need more advanced features (eg caching), you can easily cut down on 3rd party dependencies.

    import { useState, useEffect } from "react";

    function useFetch(url) {
      const [data, setData] = useState(null);
      const [loading, setLoading] = useState(true);
      const [error, setError] = useState(null);

      useEffect(() => {
        const controller = new AbortController();

        fetch(url, { signal: controller.signal })
          .then((res) => res.json())
          .then((json) => {
            console.log("Data:", json);
            setData(json);
          })
          .catch((err) => {
            if (err.name !== "AbortError") {
              console.error("Fetch error:", err);
              setError(err);
            }
          })
          .finally(() => setLoading(false));

        return () => controller.abort();
      }, [url]);

      return { data, loading, error };
    }







    function App() {
      const { data, loading, error } = useFetch("https://jsonplaceholder.typicode.com/todos/1");

      if (loading) return 

Loading...

; if (error) return

Error

; return
{JSON.stringify(data, null, 2)}
; }

Re: Show HN: Tired of logic in useEffect, I built a class-based React state manager

#12
post #10

Sorry for being pedantic, but the first example could be rewritten to extract the pattern into a higher level hook, eg useNotifications. One way to simplify components before reaching for store libraries. The reusable hook now contains all the state and effects and logic, and the component is more tidy. function Dashboard() { const { user } = useAuth(); const {loading, error, notifications, undreadCount, markAsRead}…

Far cleaner, how is testability though?

Re: Show HN: Tired of logic in useEffect, I built a class-based React state manager

#13
post #6

Earlier quoted context omitted.

For clarity, what do you call "classical OOP"? (disclaimer: FP all the way, regardless)

Essentially `new Foo()`, where `Foo` can be a subclass of `Bar` that inherits properties in the same way we all learned in our Java (or whatever actual OOP) language. JavaScript gives you a class syntax that lets you make classes and extend them from each other, and for the most part they will work the same way as a class from a language like Java ... but some things won't. You can either become an expert on prototyp…

Can you give examples of how they are different? I've only done OOP in JS so I'm not aware of what I'm missing or what's supposed to be different.

Re: Show HN: Tired of logic in useEffect, I built a class-based React state manager

#15
post #10

Sorry for being pedantic, but the first example could be rewritten to extract the pattern into a higher level hook, eg useNotifications. One way to simplify components before reaching for store libraries. The reusable hook now contains all the state and effects and logic, and the component is more tidy. function Dashboard() { const { user } = useAuth(); const {loading, error, notifications, undreadCount, markAsRead}…

Far cleaner, how is testability though?

Very easy - mock the useNotifications and you can easily see all the behaviour by changing three properties.

Re: Show HN: Tired of logic in useEffect, I built a class-based React state manager

#16
The problems OP tries to address are unfortunately a deep design flaw in mainstream frameworks like React and Vue. This is due to 2 properties they have:

1. They marry view hierarchy to state hierarchy

2. They make it very ergonomic to put state in components

I've been through this endless times. There are significant ways to reduce this friction, but in the end there's a tight ceiling.

This is why this kind of work feels like chasing a moving target. You always end up ruining something inherent to the framework in a pursuit to avoid the tons of footguns it's susceptible to.

It's also why I moved to Gleam and Lustre (elm architecture) and bid those PITAs farewell

Re: Show HN: Tired of logic in useEffect, I built a class-based React state manager

#18

Javascript and classes go together like toothpaste and orange juice. All good JS programmers I know essentially pretend that classes don't exist in the language (or if they use them, they only do so rarely, for very niche cases). JS does not have classical OOP built in! It has Brandon Eich's prototypal inheritance system (which has some key differences), along with a 2015 addition to the language to pretend it has OO…

I think the biggest issue with classes is subclassing, it looks like a good feature to have, but ends up being a problem.

If one avoids subclassing, I think classes can be quite useful as a tool to organize code and to "name" structures. In terms of performance, they offer some good optimizations (hidden class, optimized instantiation), not to mention using the memory profiler when all your objects are just instances of "Object" can be a huge pain.

Re: Show HN: Tired of logic in useEffect, I built a class-based React state manager

#19

Javascript and classes go together like toothpaste and orange juice. All good JS programmers I know essentially pretend that classes don't exist in the language (or if they use them, they only do so rarely, for very niche cases). JS does not have classical OOP built in! It has Brandon Eich's prototypal inheritance system (which has some key differences), along with a 2015 addition to the language to pretend it has OO…

I have noticed that inheritance is largely ignored by experienced developers but it's a hard argument to make that "all good JS programmers do this".

Classes are invaluable and are an extremely efficient and ergonomic way to manage state in GUI applications.

That said, avoiding classes was published in some blog post at some point and the JS hype machine went crazy with FP. As a consequence, I have yet to observe a maintainable React codebase. Good looking and performant React applications are even fewer and farther between.

Personally, writing idiomatic React has me focus too much on render cycles that I think less about how the application looks & feels. Appropriate abstractions become more difficult to conceptualize and any non-trivial application ends up a 5mb bundle with no multi-threading or optimizations. This is also what I have observed "the best JS devs" do in the wild.

Post reply on HN