Comparing Svelte and React. How do they compare in terms of ideology, behaviour and syntax?
A compiler approach to frontend frameworks.
- Single file components (SFC).
MyComponent.tsx
+MyComponent.css
->MyComponent.svelte
.
- Little boilerplate.
- Less code = less bugs.
- Less explicit code, sometimes harder to follow.
- No (required) runtime.
- Built-in CSS support.
- Scoped CSS.
- Great documentation.
- Scoped CSS implementation.
.button.s-hsgb1785
instead of.button-hsgb1785
.- Classes passed to custom components don't get hash.
- Harder to debug than React.
- Output files look quite different than src-files. Sourcemaps can help, but they can't prevent logical errors.
- No (official-ish) devtools for state management.
- https://chrome.google.com/webstore/detail/svelte-devtools/ckolcbmkjpjmangdbmnkpjigpkddpogn (doesn't cover stores).
- Smaller community and third party ecosystem.
- Harder to google things.
- Setting up TypeScript requires more work than with React.
- State management.
- Order of code blocks (e.g. reactive declarations
$: {}
) matter. - Requires VSCode plugin for syntax highlighting and intellisense (Svelte for VS Code).
React:
import React from 'react';
export function MyComponent(props) {
return (
<>
<h1>Component markup</h1>
<p>I am the component markup</p>
</>
);
}
Svelte:
<script lang="ts">
</script>
<h1>Component markup</h1>
<p>I am the component markup</p>
<style>
</style>
React:
const quiz = useSelector(getQuiz);
const dispatch = useDispatch();
...
dispatch(startQuiz());
Svelte:
const store = writable(defaultState); // https://svelte.dev/tutorial/writable-stores
$: quiz = $store.quiz; // https://svelte.dev/tutorial/reactive-declarations
...
$store.quizIsStarted = true;
React:
useEffect(() => {
doSomething(value);
}, [value]);
Svelte:
$: {
doSomething(value);
} // Svelte magically figures out the dependencies.
React:
const myRef = useRef();
...
<div ref={myRef}></div>
Svelte:
let myRef;
...
<div bind:this="{myRef}"></div>