Close Menu
Soshace Digital Blog

    Subscribe to Updates

    Get The Latest News, Updates, And Amazing Offers

    What's Hot
    SaaS & Tech

    Maximizing Efficiency: How SaaS Lowers IT Infrastructure Costs

    Remote Job

    7 Statistics About Remote Work to Make Your Company Better

    Remote Job

    Top 10 issues when hiring freelancers

    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
    Tuesday, September 9
    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 / Svelte for React Developers
    React

    Svelte for React Developers

    Adaware OgheneroBy Adaware OgheneroDecember 17, 2020Updated:December 6, 2024No Comments10 Mins Read
    Facebook Twitter Pinterest Telegram LinkedIn Tumblr Email Reddit
    Svelte for React Developers
    Share
    Facebook Twitter LinkedIn Pinterest Email Copy Link
    Svelte for React Developers
    Svelte for React Developers

    TL;DR: This article introduces Svelte to React developers. We will be explaining how different concepts in React like state, props, lifecycle methods are implemented in svelte. This will serve as a guide to get up and running with Svelte from a React developer point of view.

    Introduction

    Svelte is yet *another* SPA javascript framework in the ever-increasing list of  Javascript frameworks. Oops sorry, ignore the canned introduction for javascript frameworks. Svelte is not a framework but a compiler. Svelte compiles the component code for your SPA at build time to highly-optimized vanilla Javascript and this is what is run on your browser.

    Unlike React that ships with a virtual DOM that has to be calculated and reconciled every time the application’s state changes in the browser’s runtime. Svelte at compile-time keeps track of state that might change the DOM and whenever a piece of state changes it “surgically” updates the DOM using DOM API like createElement & setAttribute.

    The lack of a virtual DOM is one of the more significant features of Svelte, this means svelte ships less code to the client. Also Svelte is a compiler so unlike React it doesn’t ship framework-specific API like this.setState or useState that has to be parsed and executed on the browser’s runtime. Svelte code shipped to the client is pure vanilla javascript.

    Svelte’s small bundle size, performance, and awesome developer experience are some of the reasons why it stands out from the crowd of javascript frameworks released every second.

    In this article, we’ll look at how common features in React like state, props, components e.t.c are implemented in svelte.

    Components

    Components in svelte are written in a .svelte file.  In this .svelte file, you can write your HTML markup and it will be rendered unlike React where you have to create a function to return this markup.

    Example:

    //Hello.svelte
    
    <main>
       <h1>Hello World, Welcome to Svelte</h1>
    </main>

    Svelte uses its templating language built on HTML to create the component user interface. While react uses JSX which is a javascript object that compiles to DOM nodes in the browser.

    export default function App() {
      return (
        <main>
          <h1>Hello World, Welcome to Svelte</h1>
        </main>
      );
    }
    What is a component without javascript(data/state) and styling?

    Svelte give us a script tag where we will be writing javascript code/logic and a style tag where we write our CSS code. This is how a svelte component structure should look:

    <script>
      // javascript lives here
    </script>
    
    <style>
      /* css/styling lives here */
    </style>
    
    <!-- html lives everywhere else -->
    

    The style block is where styles for this component are added and these styles are scoped to this component so don’t have to worry about clashing style classes in multiple components.

    Component State

    Component state is one of the reasons we use all these javascript frontend frameworks. We want to build interactive user interfaces that react to changes in data/state.

    Creating a component state variable in Svelte is intuitive when compared to react. Let’s say we want to create a variable called `count` that would keep track of the number of times we click a button.

    <script>
      let count = 0;
    
      function handleClick() {
        count += 1;
      }
    </script>
    
    <button on:click={handleClick}>
      Clicked {count} times
    </button>
    
    //Example from svelte documentation

    Unlike React where we have to understand the useState API in order to create a state variable, in Svelte we declare state variable the same way we do in vanilla Javascript.

    Updating the state is even easier. We just assign the state to a new value. Then we added a click event on:click which calls handleClick function that updates the count by reassigning the count variable. The React equivalent would look something like this:

    export default function Button() {
      const [count, setCount] = React.useState(0)
    
      const handleClick =()=>{
        setCount((previousCount) => previousCount + 1)
      }
      return (
          <button onClick={handleClick}>Clicked {count} times</button>
      );
    }

    No much difference in terms of lines of code but need an understanding of the useState API in order to declare and update state in React.

    Read More:  React Lesson 10: Normalize Data with Immutable.js

    Props

    Props(Properties) is another commonly used feature in component-based frontend frameworks. Props allow you to pass data from a parent component to its children.

    In React passing props looks something like this:

    function Welcome(props) {
      return <h1>Hello, {props.name}</h1>;
    }
    
    function App() {
      return (
        <div>
          <Welcome name="Nero" />
          <Welcome name="Jack" />
          <Welcome name="Bruno" />
        </div>
      );
    };
    // Example from react documentation

    Props passed to a component in React can be accessed in the child component from the props object every component in React. In Svelte though the syntax seems a lot less intuitive.

    // App.svelte
    
    <script>
      import Welcome from "./Welcome.svelte";
    </script>
    
    <Welcome name="Nero" />
    <Welcome name="Jack" />
    <Welcome name="Bruno" />
    // welcome.svelte
    
    <script>
      export let name;
    </script>
    
    <h1>Hello, {name}</h1>

    When you pass a prop to a child component, you have to explicitly “accept” the props by using the export declaration. As seen in the example above, export keyword informs the Welcome component that name is a prop and not a state value.
    I know this looks awkward because export in Javascript is usually used to export modules. However, In Svelte export was modified to be used to declare props for a component.

    Component Lifecycle methods

    Components in component-based frameworks like React, Vue, Svelte e.t.c usually have a lifecycle in which they are created(mounted), updated, and destroyed (unmounted). This is similar to the cycle of life in animals i.e birth, growth, and death.

    Svelte and React give us functions/callbacks that we can run at these different cycles in a component lifecycle.

    The most popular lifecycle method for React developers would be the componentDidMount, this is run immediately after the component is mounted on the DOM.

    Most often than not this is where you initiate API calls to fetch data that is needed to initially render a component. The Svelte version of componentDidMount is called onMount.

    Below is a table of the lifecycle methods in React and the Svelte version of them:

    Svelte Lifecycle methodReact Lifecycle methodFunction/use case
    OnMount()componentDidMount()This is called as soon as the component is mounted on the DOM
    OnDestroy()componentWillUnmount()This lifecycle hook is called just before the component unmounts and is destroyed.
    beforeUpdate()–This lifecycle hook is called before the DOM has been updated by state
    afterUpdate()componentDidUpdate()This lifecycle hook is called after the DOM has been updated by state
    –shouldComponentUpdate()It can be called if you need to tell React not to re-render for a certain state or prop change. Svelte’s architecture does not create a need for this kind of hook because it re-renders only the piece of the DOM that relies on the state that was updated.

    These are some of the lifecycle methods that we might need to use in development. You can check out the Svelte documentation for other lifecycle methods like tick.

    Conditional Rendering

    React developers handle conditional rendering using native javascript conditional statements like if/else, ternary operators, and switch statements. This is because JSX compiles to regular javascript function calls and evaluates to javascript objects so it is possible to use JSX inside regular javascript conditionals.

    function Greeting({isLoggedIn}) {
      if (isLoggedIn) {
        return (<p>Welcome back</p>)
      }else{
        return (<p>please sign in</p>)
      }
    }

    However Svelte uses a template syntax to create the user interface. This template gives us a special syntax for conditionally rendering user interface components. Below is the Svelte version conditional rendering.

    <script>
      export let isLoggedIn 
    </script>
    
    <style>
    </style>
    
    {#if isLoggedIn}
      <p>Welcome back</p>
    
    {:else}
      <p>please sign in</p>
    {/if}

    With Svelte we are stuck with this if/else blocks as the only option for conditional rendering. This might take time to get familiar for React developers because we have a lot of options for conditional rendering, if/else blocks, ternary operator, switch cases, and the dreaded short-circuit AND operator(&&).

    Read More:  React and AJAX - The Art of Fetching Data in React

    Looping

    Similar to how conditional are handled in Svelte. Iterating/looping over a list of data requires us to use a special each block syntax.

    <script>
       let items = [{id: 1, name: 'nero'},{id:2, name: 'you'}] 
    </script>
    
    {#each items as item}
    	<p>{item.name}</p>
    {/each}

    However, in React we have the freedom of using all the iterator expressions in javascript(map, for-loop, foreach e.t.c)

    Data binding/ Controlled Inputs

    According to Wikipedia Data-binding is a technique that binds data sources from the provider and consumer together and synchronizes them. Usually, HTML elements like input, textarea, and select maintain their own state and update the user interface based on what is entered. In some situations, we want React/Svelte to have access to this state and to be able to control the state of this element.

    In some situations you want your component to be able to control the state of an input field. This is called a controlled input. Let’s take a look at how controlled inputs are implemented in React and Svelte.

    React:

    const SignupForm = () => {
      const [username, setUsername] = useState(' ');
      const handleChange = event => setUsername(event.target.value);
     
      return (   
          <label>
           	username:
            <input
              type="text"
              value={username}
              onChange={handleChange}
            />
          </label>
      );
    };

    A controlled input takes a  value prop and an OnChange callback that changes the value in the state.

    Svelte:

    // SignupForm.svelte 
    
    <script>
      let username = "";
    
      function setUsername(event) {
        username = event.target.value;
      }
    </script>
    
      <label>
          username:
          <input
            type="text"
            value={username}
            on:input={setUsername}
        />
    </label>

    Above is the Svelte version of the controlled input. However, Svelte gives us a better way to implement two-way data binding. Svelte has a bind:value directive that directive binds the input to the component state without the need for an on:input callback to be defined. The above can be succinctly rewritten like :

    // SignupForm.svelte  
    
    <script>
      let username = "";
    </script>
    
      <label>
          username:
          <input
            type="text"
            bind:value={username}
        />
    </label>

    This removes the need for a callback that updates the state because all the magic is done by bind:value the directive.

    Component Composition

    Component composition is a pattern in component-based FE frameworks that helps us reuse code between components. Let us take a modal for example. A modal is a component that might be reused multiple times and more often than not it doesn’t know the structure of the content it is going to render ahead of time.

    In React this can be achieved by the react children prop. A basic example demonstrating this :

    function BaseModal(props) {
      return (
        <div className=”modal”>
          {props.children}
        </div>
      );
    }

    Then other components create their own version of Modal using the base modal component.

    function WelcomeModal() {
      return (
        <BaseModal color="blue">
          <h1 className=“modal-title">
            This is the title
          </h1>
          <p className=“modal-content”>
            Here is the content
          </p>
        </BaseModal>
      );
    }
    

    Svelte doesn’t have a children prop but it implements this pattern using an HTML tag called slots. Slots allow us to render HTML or other components inside a component.

    A basic example of how component composition works in Svelte:

    // BaseModal.svelte
    
    <script>
       //Javascript logic here 
    </script>
    <style>
       /* css/styling lives here */
    </style>
    <div className=”modal”>
       <slot></slot>
    </div>

    We can then use the base modal in other components like this:

    //  WelcomeModal.svelte
    <script>
    	import BaseModal from './BaseModal.svelte';
    </script>
    
    <BaseModal>
       <h1 className=“modal-title">
          This is the title
       </h1>
       <p className=“modal-content”>
          Here is the content
       </p>
    </BaseModal>

    Other Svelte features

    Svelte has some other interesting features that you might want to look at:

    • Reactivity Statements
    • Stores

    Conclusion

    We have seen that a lot of features we use for development in react is also available in Svelte. I would give it to Svelte for making their APIs a little more developer friendly e.g declaring and updating component data. But I still need to get used to the template approach in terms of conditional rendering and looping. Svelte is an awesome frontend “framework”. Everyday people keep adopting it in their projects and the community keeps growing.

    References

    • What is Svelte’s underlying DOM manipulation strategy?
    • Svelte tutorial
    • Getting started with Svelte
    • Component composition
    Share. Facebook Twitter Pinterest LinkedIn Tumblr Email
    Adaware Oghenero

      Related Posts

      JAMstack Architecture with Next.js

      March 15, 2024

      Rendering Patterns: Static and Dynamic Rendering in Nextjs

      March 7, 2024

      Handling Mutations and Data Fetching Using React Query

      September 12, 2023
      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
      Interview March 18, 2019

      Top 18 Interview Questions for Python Developers

      Python developers can contribute a great deal to your project. The tricky thing is finding the best Python developers via well-conducted technical interview. Here’s how you should do it:

      Strategic LinkedIn Tactics for E-Commerce Lead Generation

      November 28, 2024

      Benchmark Java Applications using JMH

      December 20, 2019

      Unlock B2B Leads: Harnessing Strategic Partnerships Effectively

      November 24, 2024

      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

      Guidelines for Building Accessible Web Applications

      Programming October 21, 2019

      An In-Depth Guide to Algorithms and Data Structures

      Programming November 26, 2024

      Follow These Guidelines to Write Testable Code That Can Scale | with Examples

      Programming November 25, 2019

      Node.js Lesson 10: Nodejs as a Web Server

      Node.js November 13, 2020

      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
      Content & Leadership

      Balancing Value-Driven Content and Promotional Messaging Strategies

      LinkedIn

      Strategic LinkedIn Branding: A Key to Effective Lead Generation

      B2B Leads

      Effective Networking Strategies to Generate B2B Leads

      Most Popular

      How Deep Work Can Change Your Freelance Life

      Remote Job

      How to Take Control of Your Tech Interview | Take Charge in Three Easy Steps

      Interview

      JavaScript / Node.js Tools

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

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