Close Menu
Soshace Digital Blog

    Subscribe to Updates

    Get The Latest News, Updates, And Amazing Offers

    What's Hot
    Wiki

    Роль Менеджера Продуктов

    Entrepreneurship

    Crafting a High-Performing Team: A Startup’s Essential Guide

    Events

    React Advanced: The Tiniest Recap — See What You’ve Missed

    Important Pages:
    • Home
    • About
    • Services
    • Contact Us
    • Privacy Policy
    • Terms & Conditions
    Facebook X (Twitter) Instagram LinkedIn YouTube
    Today's Picks:
    • Scaling Success: Monitoring Indexation of Programmatic SEO Content
    • Leveraging Influencers: Key Drivers in New Product Launches
    • How Privacy-First Marketing Will Transform the Industry Landscape
    • The Impact of Social Proof on Thought Leadership Marketing
    • Balancing Value-Driven Content and Promotional Messaging Strategies
    • Top Influencer Marketing Platforms to Explore in 2025
    • Emerging Trends in Marketing Automation and AI Tools for 2023
    • Strategies to Mitigate Duplicate Content in Programmatic SEO
    Wednesday, September 10
    Facebook X (Twitter) Instagram LinkedIn YouTube
    Soshace Digital Blog
    • Home
    • About
    • Services
    • Contact Us
    • Privacy Policy
    • Terms & Conditions
    Services
    • SaaS & Tech

      Maximizing Efficiency: How SaaS Lowers IT Infrastructure Costs

      August 27, 2025

      Navigating Tomorrow: Innovations Shaping the Future of SaaS

      August 27, 2025

      Maximizing Impact: Strategies for SaaS & Technology Marketing

      August 27, 2025
    • AI & Automation

      Enhancing Customer Feedback Analysis Through AI Innovations

      August 27, 2025

      Navigating the Impact of AI on SEO and Search Rankings

      August 27, 2025

      5 Automation Hacks Every Home Service Business Needs to Know

      May 3, 2025
    • Finance & Fintech

      Critical Missteps in Finance Marketing: What to Avoid

      August 27, 2025

      Analyzing Future Fintech Marketing Trends: Insights Ahead

      August 27, 2025

      Navigating the Complex Landscape of Finance and Fintech Marketing

      August 27, 2025
    • Legal & Compliance

      Exploring Thought Leadership’s Impact on Legal Marketing

      August 27, 2025

      Maximizing LinkedIn: Strategies for Legal and Compliance Marketing

      August 27, 2025

      Why Transparency Matters in Legal Advertising Practices

      August 27, 2025
    • Medical Marketing

      Enhancing Online Reputation Management in Hospitals: A Guide

      August 27, 2025

      Analyzing Emerging Trends in Health and Medical Marketing

      August 27, 2025

      Exploring Innovative Content Ideas for Wellness Blogs and Clinics

      August 27, 2025
    • E-commerce & Retail

      Strategic Seasonal Campaign Concepts for Online and Retail Markets

      August 27, 2025

      Emerging Trends in E-commerce and Retail Marketing Strategies

      August 27, 2025

      Maximizing Revenue: The Advantages of Affiliate Marketing for E-Commerce

      August 27, 2025
    • Influencer & Community

      Leveraging Influencers: Key Drivers in New Product Launches

      August 27, 2025

      Top Influencer Marketing Platforms to Explore in 2025

      August 27, 2025

      Key Strategies for Successful Influencer Partnership Negotiations

      August 27, 2025
    • Content & Leadership

      The Impact of Social Proof on Thought Leadership Marketing

      August 27, 2025

      Balancing Value-Driven Content and Promotional Messaging Strategies

      August 27, 2025

      Analyzing Storytelling’s Impact on Content Marketing Effectiveness

      August 27, 2025
    • SEO & Analytics

      Scaling Success: Monitoring Indexation of Programmatic SEO Content

      August 27, 2025

      Strategies to Mitigate Duplicate Content in Programmatic SEO

      August 27, 2025

      Effective Data Visualization Techniques for SEO Reporting

      August 27, 2025
    • Marketing Trends

      How Privacy-First Marketing Will Transform the Industry Landscape

      August 27, 2025

      Emerging Trends in Marketing Automation and AI Tools for 2023

      August 27, 2025

      Maximizing ROI: Key Trends in Paid Social Advertising

      August 27, 2025
    Soshace Digital Blog
    Blog / JavaScript / React Hooks + RxJS or How React Is Meant to Be
    JavaScript

    React Hooks + RxJS or How React Is Meant to Be

    Kirill NovikBy Kirill NovikJuly 31, 2019Updated:July 31, 2019No Comments10 Mins Read
    Facebook Twitter Pinterest Telegram LinkedIn Tumblr Email Reddit
    React Hooks + RxJS or How React Is Meant to Be
    React Hooks + RxJS or How React Is Meant to Be
    Share
    Facebook Twitter LinkedIn Pinterest Email Copy Link
    artwork depicting React and RxJS logo with a hook
    We’re hooked!

    I remember when I first got introduced to React. I was stunned by how great the idea of handling all of the presentation logic with just javascript and JSX was, and even more so: how effortless it seemed at first–you pass in props, update states. How easy!

    Going through the first Tic-Tac-Toe tutorial on the React homepage felt so great, I was confident that humanity has finally found the magic bullet, at least for the front-end.

    But… there was a caveat. What if we lifted the state five floors up, but some of that state and state update logic was still needed on the first floor?

    How about we pass some state one level down, then some of that state one level further and so on till it reaches the component? That’s a bit laborious but ok.

    Oh, I forget, I need to change the shape of the state on the fifth floor… and props on the fourth… and props on the third… second… first…

    Ouch! Is it by mistake or design? Turns out this state-to-props issue is by design, and this is where Redux steals the show. However, five minutes into the Redux tutorial you begin to realize that your excitement about React was an overreaction… or was it?

    There were many attempts I know of to steal the show back for React, to name a few: React Context API as well as various state managers; but for me, none of them got the excitement I initially had for React back… except when I learned about RxJS.

    Analysis

    This article’s main goal is to justify that the RxJS and React combo allows for better readability, less boilerplate and being closer to React while allowing the same functionality as the popular state management frameworks and not being a framework itself. Let’s look at this approach more closely.

    Better readability & less boilerplate

    Artwork depicting code mockup that the developer who wrote it doesn't recognize
    We’ve all had these moments

    Readability is one of the first things I pay attention to as I choose a tool I am going to be working with. For me, the main criterion upon which I evaluate the quality of my own code is how well am I able to understand it a week after and a month after it was written.

    Of course, the tool you are using isn’t always as impacting on your code readability and self-documentability as much as your own set of habits and choices, but it still may be a contributing factor nonetheless. In my experience, the more verbosity and indirection is associated with creating a specific functionality, the less you will be able to understand it later on.

    And this is true of Redux. Before even getting to the core of what it is you are doing, you have to write your actions (some people write action creators on top of that), create reducers, compose them, connect dispatch and state to props, and only then introduce the logic, and don’t forget you have to write sagas or thunks for side effects.

    When you are trying to understand the structure of a Redux application, you are facing similar challenges, you have to understand what actions trigger what side effects, what happens in reducers and how it all fits together. I’ve always considered it being a nightmare, and, despite my many attempts, never really understood my colleagues who were very passionate about Redux. I would say Redux and readability are essentially the opposites. Feel free to disagree, but please make an educated argument in the comments for me and other people to be able to learn.

    Read More:  Node.js Lesson 3: Node Package Manager

    MobX significantly improves the readability aspect by not having the verbosity and indirection of Redux. Yet it can be confusing to mentally derive the structure of the state that consists of composed stores, as they can become a mess of properties and update logic. So how does it compare to the RxJS Hook?

    Since you’re essentially using RxJS Hook as the familiar useState hook, it should be very easy to read and understand. Your state lives inside of a Subject that you can always retrieve later and analyze as you are trying to understand what the application is doing.

    Close to React

    artwork depicting various parts of the React ecosystem
    It’s quite an atomic family

    React is elegant. The state managers are not. Period. If there is an opportunity to stay with React before introducing other frameworks, I will use that opportunity. I am convinced that you should be able to compose complex and elegant application code with essentially React and Services logic while not sacrificing readability, maintainability, and scalability.

    RxJS and React Hooks are actually the combination I find extremely helpful in this regard. Having actually written production code with this, I can tell you from my experience that it was and still is a great ride.

    State Management Functionality

    artwork depicting various stages of an atom
    Creation of the modern front-end universe

    I never really understood the popularity of Redux. Don’t get me wrong, I always thought it was pretty interesting, but I never liked writing my code using it. I wonder if its popularity really comes from the fact that people like Dan Abramov, who is a great guy and a great engineer, but it doesn’t make sense why it would still worth biting the bullet.

    The main merit of Redux for me is in its three principles of course, which are:

    • Single source of truth
    • State is read-only
    • Changes are made by pure functions

    So none of these principles actually work for MobX! With MobX you don’t have a centralized state object. You have a centralized store object. Know the difference. 😉
    And since you don’t have a centralized state object, you can’t use it to easily reason about your application as your stores and your state are interleaved and can be pretty hard to unravel.

    With RxJS Subjects and React Hooks we get the one principle out of the box – the pure-functions, as observable streams are themselves pure-functions. Unfortunately, the state of a BehaviorSubject is not read-only, and you can manually change it after you get it with getValue(). I will try to ask the community if it is possible to make it read-only out of the box so that you can’t shoot yourself in the foot with this, as I am pretty sure it could just be something the contributors have overlooked. But as to the single source of truth, it is actually not that difficult to introduce by composing all the subjects into one observable, similar to how you compose reducers together.

    Single Source of Truth

    const subject001 = new BehaviorSubject({});
    const subject002 = new BehaviorSubject({});
    const subject003 = new BehaviorSubject({});
    
    // Only for listening
    const globalObservable = combineLatest(subject001, subject002, subject003);

    In general, the RxJS Hook approach is not that different from Flux. You have:

    • Dispatcher/action – subject.next() / setSharedState()
    • Store – globalObservable
    • View – well, your view

    TL;DR

    So here is your shared state!

    const subject = new BehaviorSubject({ message: '' });
    
    const AwesomeComponent = () => {
     const [{ message }, setState] = useSharedState(subject); // Custom Hook
     return <div>{message}</div>;
    };

    Nothing unusual: we are getting a tuple of value and setState function.

    Read More:  RxJS Introduction

    Do you want to use it like useState?

    Easy!

    const AwesomeComponent = () => {
     const [{ message }, setState] = useSharedState(subject);
     return <div
       onClick={() => setState({ message: 'test' })} // One way
       onClick={() => subject.next({ message: 'test' })} // Another way
     >{message}</div>;
    };

    subject.next is another way to update the logic, but I think setState from the tuple makes it more readable and easy to understand.

    Do you want it to be shared between components at the top of the tree as well as the bottom?

    Easy!

    const First = () => {
     const [{ message }, setState] = useSharedState(subject);
     return <div>First: {message}</div>
    }
    const Second = () => <div><First/></div>
    const Third = () => <div><Second/></div>
    const Fourth = () => <div><Third/></div>
    
    const Fifth = () => {
     const [{ message }, setState] = useSharedState(subject);
     return <div><div>Fifth: {message}<div><Fourth/></div>
    }

    Notice that we can use the same state easily, where in the past you would have to pass everything through props.

    Do you want to use both local and shared states?

    Easy!

    // Single shared and local states
    const AwesomeComponent = () => {
     const [sharedState, setSharedState] = useSharedState(subject);
     const [state, setState] = useState(‘’);
     return <div>{/* That was easy */}</div>;
    };
    
    // Multiple shared and local states
    const AwesomeComponent = () => {
     const [sharedState001, setSharedState001] = useSharedState(subject001);
     const [sharedState002, setSharedState002] = useSharedState(subject002);
     const [sharedState003, setSharedState003] = useSharedState(subject003);
     const [state001, setState001] = useState('test');
     const [state002, setState002] = useState('test');
     const [state003, setState003] = useState('test');
     return <div>{/* That was easy */}</div>;
    };

    Another great thing is that you actually can have multiple little states as part of your component state.

    Oh, but what if I want to update this state outside the component…

    Easy!

    subject.next({ message: 'I know Kung Fu' });
    artwork depicting Neo from the Matrix movie
    Or so the course certificate says

    You can update state from anywhere in the application, by just using subject.next. It is extremely useful! MobX and Redux could never give you this much freedom.

    Still not convinced?

    I rewrote the Redux tutorial using the RxJS Hooks approach. Feel free to compare two codebases that do the same thing. Here‘s the original Redux Reddit Tutorial and here‘s the React + RxJS Reddit Tutorial.

    Side Notes

    I think somebody brought to my attention that using components with subjects makes them tightly coupled. It is true in a sense where, for example, you are importing something from an external library which makes a hard dependency. But having hard dependencies doesn’t mean you can’t make whatever it is you are building highly reusable. A styled component inside of my custom component is a hard dependency, but it is abstracted out when I import my custom component. The same goes for this approach.

    Conclusion

    Behind the custom hook is a little pretty eight-liner:

    const useSharedState = subject => {
     const [value, setState] = useState(subject.getValue());
     useEffect(() => {
       const sub = subject.pipe(skip(1)).subscribe(s => setState(s));
       return () => sub.unsubscribe();
     });
     const newSetState = state => subject.next(state);
     return [value, newSetState];
    };
    artwork depicting Neo from the Matrix movie
    Just an ordinary day of a React developer

    Is this really new?

    Not really, there are many blog posts about similar concepts, but in my opinion, people always slide into the complexity trap and start to introduce new frameworks.

    This article is almost a mirror of this one. I didn’t know there was an article about essentially the same thing. I assure you I came up with this independently. But this doesn’t really matter. What matters is to be faithful to React’s promise: React makes it painless to create interactive UIs. and try to avoid the unnecessary complexity of introducing a new state manager or a framework, this is so besides the point! (Sorry Akita, but you fell into that trap)

    Share. Facebook Twitter Pinterest LinkedIn Tumblr Email
    Kirill Novik

      Related Posts

      Mastering REST APIs: Essential Techniques for Programmers

      December 18, 2024

      Streamlining Resource Allocation for Enhanced Project Success

      December 18, 2024

      Crafting Interactive User Interfaces Using JavaScript Techniques

      December 17, 2024
      Leave A Reply Cancel Reply

      You must be logged in to post a comment.

      Stay In Touch
      • Facebook
      • Twitter
      • Pinterest
      • Instagram
      • YouTube
      • Vimeo
      Don't Miss
      Programming October 19, 2016

      19. Уроки Node.js. Безопасный Путь к Файлу в fs и path.

      В этой статье мы рассмотрим, как при помощи Node.js создать веб-сервер, который будет возвращать файл пользователю из директории public. Может возникнуть вопрос: зачем здесь Node.js? почему бы не сделать это на другом сервере? Вопрос совершенно уместен. Да, для отдачи файлов, как правило, другие сервера будут более эффективны. С другой стороны, Node.js, во-первых, тоже работает весьма неплохо, а во-вторых, перед отдачей файла может совершить какие-то интеллектуальные действия, например, обратиться к базе данных, проверить, имеет ли пользователь право на доступ к данному файлу, и только если имеет, тогда уже отдавать.

      Facebook Ads vs Google Ads: Which Works Best for Home Services?

      May 3, 2025

      6 Reasons to Integrate AI into Software Testing

      September 3, 2019

      Bootstrap: TOP 5 Free Bootstrap Editors & Tools

      May 28, 2019

      Categories

      • AI & Automation
      • Angular
      • ASP.NET
      • AWS
      • B2B Leads
      • Beginners
      • Blogs
      • Business Growth
      • Case Studies
      • Comics
      • Consultation
      • Content & Leadership
      • CSS
      • Development
      • Django
      • E-commerce & Retail
      • Entrepreneurs
      • Entrepreneurship
      • Events
      • Express.js
      • Facebook Ads
      • Finance & Fintech
      • Flask
      • Flutter
      • Franchising
      • Funnel Strategy
      • Git
      • GraphQL
      • Home Services Marketing
      • Influencer & Community
      • Interview
      • Java
      • Java Spring
      • JavaScript
      • Job
      • Laravel
      • Lead Generation
      • Legal & Compliance
      • LinkedIn
      • Machine Learning
      • Marketing Trends
      • Medical Marketing
      • MSP Lead Generation
      • MSP Marketing
      • NestJS
      • Next.js
      • Node.js
      • Node.js Lessons
      • Paid Advertising
      • PHP
      • Podcasts
      • POS Tutorial
      • Programming
      • Programming
      • Python
      • React
      • React Lessons
      • React Native
      • React Native Lessons
      • Recruitment
      • Remote Job
      • SaaS & Tech
      • SEO & Analytics
      • Soshace
      • Startups
      • Swarm Intelligence
      • Tips
      • Trends
      • Vue
      • Wiki
      • WordPress
      Top Posts

      Freelance Programming Is Great — but Is It for You?

      Remote Job September 27, 2019

      How Facebook Ads Can Skyrocket Your Home Services Bookings

      Facebook Ads May 3, 2025

      Fundamentals of Programming: A Beginner’s Guide

      Programming November 25, 2024

      Where to Hire Remote Developers

      JavaScript July 12, 2018

      Subscribe to Updates

      Get The Latest News, Updates, And Amazing Offers

      About Us
      About Us

      Soshace Digital delivers comprehensive web design and development solutions tailored to your business objectives. Your website will be meticulously designed and developed by our team of seasoned professionals, who combine creative expertise with technical excellence to transform your vision into a high-impact, user-centric digital experience that elevates your brand and drives measurable results.

      7901 4th St N, Suite 28690
      Saint Petersburg, FL 33702-4305
      Phone: 1(877)SOSHACE

      Facebook X (Twitter) Instagram Pinterest YouTube LinkedIn
      Our Picks
      Interview

      Best Resources for Preparing for Your Technical Interview: Books and Online Platforms

      Programming

      Уроки React. Урок 13. Часть 1.

      Interview

      An Interview with a Freelancer Who Actually Ended Up on the Island: “I Live and Code in a Paradise”

      Most Popular

      Hunting Down and Fixing Memory Leaks in Java

      Java

      Node.js Lesson 10: Nodejs as a Web Server

      Node.js

      JavaScript find() and filter() Array Iteration Methods Made Easy

      JavaScript
      © 2025 Soshace Digital.
      • Home
      • About
      • Services
      • Contact Us
      • Privacy Policy
      • Terms & Conditions

      Type above and press Enter to search. Press Esc to cancel.