Hacker News new | ask | show | jobs
by mixedCase 2611 days ago
Speaking for Redux at least: developer tool integration, mindshare and doesn't shoehorn OOP into an FP approach to UI.

What are the advantages of this solution over features already in React (no need of Redux) such as context and the reduce hook?

2 comments

> doesn't shoehorn OOP into an FP approach to UI

Functional UI is still need some sort of imperative shell [1] to manage state. You can use OOP and Remold just for "reactive" behaviour, and implement all state transitions inside object in a functional way. For example:

    // Pure function
    const addProduct = (order, product) => ({
        total: order.total + product.price,
    });
    
    // Imperative state
    class Order extends Remold {
        state = {
            total: 0
        };        

        @act setState(newState) { this.state = newState; }

        addProduct(p) { this.setState(addProduct(this.state, p)); }
    }

> What are the advantages of this solution over features already in React (no need of Redux) such as context and the reduce hook?

From the React Documentation about Context feature [2]:

> Apply it sparingly because it makes component reuse more difficult.

With Remold you don't have any problems with component's reusability. You just attach pure component to an object and "connect" object's state into component's props:

    // Pure component
    const OrderWidget = ({ total }) => <div class="widget">{total}</div>;
    
    // Pure function
    const addProduct = (order, product) => ({
        total: order.total + product.price,
    });
    
    // Imperative state
    class Order extends Remold {
        state = {
            total: 0
        };        

        @act setState(newState) { this.state = newState; }

        addProduct(p) { this.setState(addProduct(this.state, p)); }
        
        @mold(OrderWidget) asWidget() { return { total: this.state.total }; }
    }

[1] https://www.destroyallsoftware.com/talks/boundaries

[2] https://reactjs.org/docs/context.html?no-cache=1#before-you-...

Redux also has some more nice features around middleware which is great for data interception and manipulation, and selectors which can be great for performance if memoized. Also, you don't need redux for it, but the idea of separating pure view code and code that does network calls and implements business logic is really useful.

At the end of the day, you can write whatever you want from scratch, but it becomes a cost/benefit analysis.

I like this repo for getting into the guts of how popular tech works: https://github.com/danistefanovic/build-your-own-x