DEV Community

Cover image for React Strict DOM package
Ricardo Esteves
Ricardo Esteves

Posted on

React Strict DOM package

Hi Dev's

After the React team announcement to all the improvements that React v19 will bring, including the awesome introduction of a compiler. The React team is working on a truly exciting package that I believe is worth your time.

In the dynamic landscape of web and native application development, achieving cross-platform consistency while preserving performance and reliability remains a formidable challenge. Meta's recent release of React Strict DOM introduces a paradigm shift in this realm. In this expansive exploration, we embark on a journey to uncover the depths of React Strict DOM, elucidating its novel features, advantages, disadvantages, and the transformative potential it holds for universal React component development.

The Genesis of React Strict DOM: A New Era in Universal Components

React Strict DOM emerges as a revolutionary addition to the React ecosystem, poised to redefine the way developers create and deploy universal components for web and native platforms. By leveraging a novel integration of React DOM and StyleX, React Strict DOM empowers developers to seamlessly craft styled React components that transcend platform boundaries.

Understanding the New React Strict DOM Package: Features and Purpose

At its core, React Strict DOM serves as an experimental integration of React DOM and StyleX, offering a subset of imperative DOM and CSS functionalities tailored to support both web and native targets. The primary goal of React Strict DOM is to streamline and standardize the development of styled React components, enhancing development speed, efficiency, and code maintainability across diverse platforms.

Advantages of React Strict DOM: Accelerating Development Efficiency

  1. Speed and Efficiency: React Strict DOM enhances the speed and efficiency of React development by providing a unified platform-agnostic API for creating styled components.
  2. Performance and Quality: Despite its experimental nature, React Strict DOM does not compromise on performance, reliability, or code quality, ensuring optimal user experiences across platforms.
  3. Standardization: By standardizing the development process, React Strict DOM promotes consistency and code maintainability, facilitating collaboration and code reuse across projects.

Disadvantages of React Strict DOM: Addressing Limitations and Challenges

  1. Experimental Nature: As an experimental integration, React Strict DOM may entail potential issues or limitations that are yet to be fully explored or documented, necessitating careful consideration and testing.
  2. Compatibility Challenges: While React Strict DOM aims to support both web and native platforms, compatibility with React Native remains a work in progress, presenting challenges for developers seeking seamless integration across diverse environments.

Solving the Development Dilemma: Addressing Cross-Platform Challenges

React Strict DOM addresses the perennial challenge of developing styled React components for both web and native platforms in a standardized, efficient, and performant manner. By leveraging the strengths of React DOM and StyleX, React Strict DOM bridges the gap between web and native development paradigms, empowering developers to create universal components with ease.

The Concept Behind React Strict DOM: Polyfills and Web API Integration

At its conceptual core, React Strict DOM builds upon the design goals of the "React DOM for Native proposal" by polyfilling a myriad of standard APIs and leveraging emerging web capabilities in React Native, such as DOM traversal and layout APIs. By integrating these capabilities with a well-defined event loop processing model, React Strict DOM paves the way for seamless cross-platform development experiences.

Exploring React Strict DOM Through Code: A Technical Deep Dive

Creating components with react-strict-dom
react-strict-dom is powered by stylex which is a new styling solution created by Meta that is already powering facebook.com in production. It comes with the package under css module. All the building blocks with which we can build our app are available under html. This is how building UI with RSD looks like:



import React from "react";
import { css, html } from "react-strict-dom";

export default function App() {
  return (
    <html.div style={styles.div}>
      <html.div data-testid="testid">div</html.div>
      <html.span>span</html.span>
      <html.p>paragraph</html.p>

      <html.div />

      <html.span>
        <html.a href="https://google.com">anchor</html.a>,
        <html.code>code</html.code>,<html.em>em</html.em>,
        <html.strong>strong</html.strong>,
        <html.span>
          H<html.sub>2</html.sub>0
        </html.span>
        ,<html.span>
          E=mc<html.sup>2</html.sup>
        </html.span>
      </html.span>
    </html.div>
  );
}


const styles = css.create({
  div: {
    paddingBottom: 50,
    paddingTop: 50,
    backgroundColor: "white",
  },
});


Enter fullscreen mode Exit fullscreen mode

react-strict-dom is leveraging APIs that we know from the Web to build universal apps.

Is <html.div> a native component?
Yes, it is! The role of react-strict-dom is to translate one universal API to platforms' primitives.

Let's delve into a series of intricate code examples that showcase the power and versatility of React Strict DOM:

  • 1. Defining Styles with StyleX


import { css } from 'react-strict-dom';

const styles = css.create({
  container: {
    flexDirection: 'row',
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: 'lightblue',
    padding: 20,
    borderRadius: 8,
  },
  text: {
    fontSize: 18,
    fontWeight: 'bold',
    color: 'white',
  },
});


Enter fullscreen mode Exit fullscreen mode
  • 2. Creating a Styled Component


import { html } from 'react-strict-dom';

const StyledComponent = () => {
  return (
    <html.div style={styles.container}>
      <html.span style={styles.text}>Styled Component</html.span>
    </html.div>
  );
};

export default StyledComponent;


Enter fullscreen mode Exit fullscreen mode
  • 3. Rendering Text Elements


const TextComponent = () => {
  return (
    <html.div>
      <html.p>This is a paragraph.</html.p>
      <html.span>This is a span.</html.span>
      <html.h1>This is a heading.</html.h1>
    </html.div>
  );
};


Enter fullscreen mode Exit fullscreen mode
  • 4. Working with Lists


const ListComponent = () => {
  const items = ['Item 1', 'Item 2', 'Item 3'];

  return (
    <html.ul>
      {items.map((item, index) => (
        <html.li key={index}>{item}</html.li>
      ))}
    </html.ul>
  );
};


Enter fullscreen mode Exit fullscreen mode
  • 5. Handling Events


const ButtonComponent = () => {
  const handleClick = () => {
    console.log('Button clicked');
  };

  return (
    <html.button onClick={handleClick}>Click Me</html.button>
  );
};


Enter fullscreen mode Exit fullscreen mode
  • 6. Conditionally Rendering Components


const ConditionalComponent = ({ condition }) => {
  return condition ? <html.div>Condition is true</html.div> : <html.div>Condition is false</html.div>;
};


Enter fullscreen mode Exit fullscreen mode
  • 7. Passing Props to Components


const PropsComponent = ({ name }) => {
  return <html.div>Hello, {name}!</html.div>;
};


Enter fullscreen mode Exit fullscreen mode
  • 8. Using Fragments


const FragmentComponent = () => {
  return (
    <>
      <html.div>Fragment Component</html.div>
      <html.div>Another Fragment Component</html.div>
    </>
  );
};


Enter fullscreen mode Exit fullscreen mode
  • 9. Styling Components Inline


const InlineStyleComponent = () => {
  const inlineStyle = { color: 'red', fontSize: '18px' };

  return <html.div style={inlineStyle}>Inline Style Component</html.div>;
};


Enter fullscreen mode Exit fullscreen mode
  • 10. Implementing Component Lifecycle Methods


class LifecycleComponent extends React.Component {
  componentDidMount() {
    console.log('Component mounted');
  }

  componentWillUnmount() {
    console.log('Component will unmount');
  }

  render() {
    return <html.div>Lifecycle Component</html.div>;
  }
}


Enter fullscreen mode Exit fullscreen mode
  • 11. Using Hooks


import { useState } from 'react-strict-dom';

const HooksComponent = () => {
  const [count, setCount] = useState(0);

  return (
    <>
      <html.div>Count: {count}</html.div>
      <html.button onClick={() => setCount(count + 1)}>Increment</html.button>
    </>
  );
};


Enter fullscreen mode Exit fullscreen mode
  • 12. Handling Form Inputs


const FormComponent = () => {
  const [value, setValue] = useState('');

  const handleChange = (e) => {
    setValue(e.target.value);
  };

  return (
    <html.div>
      <html.input type="text" value={value} onChange={handleChange} />
      <html.div>Typed Value: {value}</html.div>
    </html.div>
  );
};


Enter fullscreen mode Exit fullscreen mode
  • 13. Using Context API


import { createContext, useContext } from 'react-strict-dom';

const ThemeContext = createContext('light');

const ThemeComponent = () => {
  const theme = useContext(ThemeContext);



  return <html.div>Current Theme: {theme}</html.div>;
};


Enter fullscreen mode Exit fullscreen mode
  • 14. Implementing Error Boundaries


class ErrorBoundary extends React.Component {
  constructor(props) {
    super(props);
    this.state = { hasError: false };
  }

  componentDidCatch(error, errorInfo) {
    console.error('Error caught:', error);
    this.setState({ hasError: true });
  }

  render() {
    if (this.state.hasError) {
      return <html.div>Error Encountered!</html.div>;
    }
    return this.props.children;
  }
}


Enter fullscreen mode Exit fullscreen mode
  • 15. Implementing Higher-Order Components


const withLogger = (Component) => {
  return class extends React.Component {
    componentDidMount() {
      console.log('Component mounted:', Component.name);
    }

    render() {
      return <Component {...this.props} />;
    }
  };
};

const EnhancedComponent = withLogger(MyComponent);


Enter fullscreen mode Exit fullscreen mode

Conclusion: Embracing the Future of Cross-Platform Development

In conclusion, React Strict DOM emerges as a game-changing innovation in the realm of universal React component development. By offering a standardized, efficient, and performant solution for crafting styled components across web and native platforms, React Strict DOM heralds a new era of cross-platform development. As developers embrace the transformative potential of React Strict DOM, they unlock new possibilities for creating immersive, platform-agnostic user experiences that transcend traditional boundaries. Welcome to the future of cross-platform development with React Strict DOM.

It's still in experimental faze but it looks really promising.

Follow me @ricardogesteves
X(twitter)

RicardoGEsteves (Ricardo Esteves) Β· GitHub

Full-Stack Developer | Passionate about creating intuitive and impactful user experiences | Based in Lisbon, Portugal πŸ‡΅πŸ‡Ή - RicardoGEsteves

favicon github.com

Top comments (2)

Collapse
 
wakie87 profile image
Scott Wakefield

Hey Ricardo, Im chasing a dev. Can you drop me an email to scott@npclinics.com.au Cheers :)

Collapse
 
ricardogesteves profile image
Ricardo Esteves

Hi Scott, ok I will send you an mail.