·10 min read

React vs Vue Code Example: A Side-by-Side Comparison

Choosing a front-end framework is one of the most crucial decisions in modern web development. React and Vue are two giants in the space, each boasting expansive communities and widespread use. But how do they differ in practice? This article presents a thorough React vs Vue code example comparison, allowing both seasoned developers and curious newcomers to gauge how these frameworks stack up when faced with common tasks.

Understanding the Core Concepts

Before diving into a React vs Vue code example for each use case, it’s important to appreciate the philosophies underpinning these libraries. React, developed by Facebook, is a robust library focused on building user interfaces via a component-based approach, emphasizing JavaScript logic with JSX syntax. Vue, crafted by Evan You, offers a progressive framework experience with a gentle learning curve, adopting templates reminiscent of classic HTML but with powerful reactivity baked in.

While both foster component-driven development, their syntax, state management, and opinions about best practices create different developer experiences.

Setting the Stage: Project Setup

A side-by-side React vs Vue code example often begins with the scaffolding process.

React:

npx create-react-app my-react-app

Vue:

npm install -g @vue/cli
vue create my-vue-app

Both commands generate a development-ready environment, bundling essential tools and hot module replacement. From here, let’s move into the heart of the comparison—the code.

Component Basics: Hello World

Let’s start with the classic "Hello World" as our first React vs Vue code example. This fundamental test spotlights template structure, syntax clarity, and boilerplate requirements.

React

import React from 'react';
 
function App() {
  return (
    <div>
      <h1>Hello World from React!</h1>
    </div>
  );
}
 
export default App;

Vue

<template>
  <div>
    <h1>Hello World from Vue!</h1>
  </div>
</template>
 
<script>
export default {
  name: 'App',
};
</script>

While both are concise, Vue’s single-file components distinctly separate markup, script, and styling, whereas React blends markup within JavaScript through JSX. Both approaches are easy to read, but Vue’s format can feel familiar to those with HTML and CSS backgrounds.

Rendering Lists: Dynamic Content

For many applications, rendering lists is a bread-and-butter task. In this React vs Vue code example, we’ll loop through an array of items and display them in a list.

React

function ItemList() {
  const items = ['Apple', 'Banana', 'Cherry'];
 
  return (
    <ul>
      {items.map((item, index) => <li key={index}>{item}</li>)}
    </ul>
  );
}

Vue

<template>
  <ul>
    <li v-for="(item, index) in items" :key="index">{{ item }}</li>
  </ul>
</template>
 
<script>
export default {
  data() {
    return {
      items: ['Apple', 'Banana', 'Cherry']
    };
  }
}
</script>

The key distinction in this React vs Vue code example lies in how logic intertwines with markup. React relies on embedding JavaScript directly, while Vue uses directives (v-for) and data objects for a clearer demarcation between data and template.

Handling Events: Interactivity

Interactivity is at the core of modern web applications. Let’s look at a React vs Vue code example for handling a simple button click event that increments a counter.

React

import React, { useState } from 'react';
 
function Counter() {
  const [count, setCount] = useState(0);
 
  return (
    <div>
      <p>You clicked {count} times.</p>
      <button onClick={() => setCount(count + 1)}>Click Me</button>
    </div>
  );
}

Vue

<template>
  <div>
    <p>You clicked {{ count }} times.</p>
    <button @click="count++">Click Me</button>
  </div>
</template>
 
<script>
export default {
  data() {
    return {
      count: 0
    };
  }
}
</script>

React’s use of useState provides clear, explicit state management for functional components. Vue’s approach integrates state directly into the component’s data, with concise event binding using @click. Both empower rapid prototyping and scale gracefully with growing complexity.

Two-Way Binding: Keeping Data in Sync

Among the nuanced differences in this React vs Vue code example series, two-way data binding is a major separator. Vue allows for two-way binding out of the box, while React prefers one-way data flow.

React

function NameInput() {
  const [name, setName] = useState('');
 
  return (
    <div>
      <input value={name} onChange={e => setName(e.target.value)} />
      <p>Your name is: {name}</p>
    </div>
  );
}

Vue

<template>
  <div>
    <input v-model="name" />
    <p>Your name is: {{ name }}</p>
  </div>
</template>
 
<script>
export default {
  data() {
    return {
      name: ''
    };
  }
}
</script>

Vue’s v-model directive binds the input and model seamlessly, while React handles updates through an explicit handler. Both are readable, but Vue’s shorthand can significantly simplify form-heavy applications.

Conditional Rendering: Show or Hide Content

Almost every interface needs to conditionally render elements. Comparing React vs Vue code example for toggling UI:

React

function ShowHide() {
  const [visible, setVisible] = useState(true);
 
  return (
    <div>
      <button onClick={() => setVisible(!visible)}>
        {visible ? 'Hide' : 'Show'} Message
      </button>
      {visible && <p>The message is visible!</p>}
    </div>
  );
}

Vue

<template>
  <div>
    <button @click="visible = !visible">
      {{ visible ? 'Hide' : 'Show' }} Message
    </button>
    <p v-if="visible">The message is visible!</p>
  </div>
</template>
 
<script>
export default {
  data() {
    return {
      visible: true
    };
  }
}
</script>

Vue’s v-if makes toggling content extremely approachable. In React, conditional rendering is a natural fit within JSX—both patterns are compact, but developers who prefer declarative HTML may favor Vue’s approach.

Props and Component Communication

Component communication is critical for scalable UI architectures. Reviewing a React vs Vue code example on passing data from a parent to a child:

React (Parent and Child)

function Parent() {
  return <Child message="Hello from parent!" />;
}
 
function Child({ message }) {
  return <div>{message}</div>;
}

Vue (Parent and Child)

<!-- Parent.vue -->
<template>
  <ChildComponent message="Hello from parent!" />
</template>
<script>
import ChildComponent from './ChildComponent.vue'
export default {
  components: { ChildComponent }
}
</script>
 
<!-- ChildComponent.vue -->
<template>
  <div>{{ message }}</div>
</template>
<script>
export default {
  props: ['message']
}
</script>

Both frameworks empower seamless data flow via props. In this React vs Vue code example, the clarity of Vue’s props declaration within the <script> tag can help avoid confusion as projects grow.

Lifecycle Hooks: Reactivity in Action

Managing side effects during a component’s lifecycle is another area ripe for a React vs Vue code example. This comparison shows how both frameworks achieve similar goals differently.

React

import React, { useEffect } from 'react';
 
function Timer() {
  useEffect(() => {
    console.log('Component Mounted');
    return () => console.log('Component Unmounted');
  }, []);
 
  return <div>Timer Component</div>;
}

Vue

<template>
  <div>Timer Component</div>
</template>
 
<script>
export default {
  mounted() {
    console.log('Component Mounted');
  },
  unmounted() {
    console.log('Component Unmounted');
  }
}
</script>

React’s useEffect handles lifecycle events in a single hook, accommodating mounting, unmounting, and updates. Vue splits lifecycle methods for mounting and unmounting, which can make intentions immediately clear to maintainers.

Styling Components: CSS Integration

Styling strategy often determines workflow familiarity and reusability. Let’s look at styling in both frameworks using a simple React vs Vue code example.

React (CSS-in-JS)

function StyledButton() {
  const style = {
    backgroundColor: 'skyblue',
    padding: '10px',
    border: 'none',
    borderRadius: '4px'
  };
 
  return <button style={style}>Styled Button</button>;
}

Vue (Scoped CSS)

<template>
  <button class="styled-button">Styled Button</button>
</template>
 
<style scoped>
.styled-button {
  background-color: skyblue;
  padding: 10px;
  border: none;
  border-radius: 4px;
}
</style>

React’s approach leverages inline styles or CSS-in-JS solutions, empowering programmatic styling. Vue champions scoped CSS within single-file components, allowing predictable CSS encapsulation.

Advanced Patterns: Context API vs Provide/Inject

Complex applications need more robust state management and data sharing across component trees. Here’s a React vs Vue code example showcasing these advanced patterns.

React: Context API

import React, { createContext, useContext } from 'react';
 
const MyContext = createContext();
 
function Parent() {
  return (
    <MyContext.Provider value="Shared Data">
      <Child />
    </MyContext.Provider>
  );
}
 
function Child() {
  const data = useContext(MyContext);
  return <div>{data}</div>;
}

Vue: Provide/Inject

<!-- ParentComponent.vue -->
<template>
  <ChildComponent />
</template>
 
<script>
export default {
  provide() {
    return {
      sharedData: 'Shared Data'
    };
  }
}
</script>
 
<!-- ChildComponent.vue -->
<template>
  <div>{{ sharedData }}</div>
</template>
<script>
export default {
  inject: ['sharedData']
}
</script>

React’s Context API is more verbose but offers granular control. Vue’s provide/inject is succinct, which can enhance readability but should be used with care to maintain transparency in large projects.

Form Validation: Practical User Input Handling

Front-end forms demand robust validation. In our React vs Vue code example, we’ll focus on a simple form input with basic validation feedback.

React

function SimpleForm() {
  const [input, setInput] = useState('');
  const [error, setError] = useState('');
 
  const handleChange = e => {
    setInput(e.target.value);
    setError(e.target.value.length < 3 ? 'Too short!' : '');
  };
 
  return (
    <div>
      <input value={input} onChange={handleChange} />
      {error && <span style={{ color: 'red' }}>{error}</span>}
    </div>
  );
}

Vue

<template>
  <div>
    <input v-model="input" @input="validate" />
    <span v-if="error" style="color: red">{{ error }}</span>
  </div>
</template>
<script>
export default {
  data() {
    return {
      input: '',
      error: ''
    };
  },
  methods: {
    validate() {
      this.error = this.input.length < 3 ? 'Too short!' : '';
    }
  }
}
</script>

While React handles validation logic directly within event handlers, Vue utilizes reactive methods, often resulting in less code for similar behavior.

Ecosystem and Tooling

No React vs Vue code example review is complete without discussing extensibility. React enjoys immense ecosystem support—tools like Redux, React Router, and React Query fuel scalable apps. Vue counters with Vue Router, Vuex (or Pinia for state), and an elegant CLI. Both offer robust plugin architectures, developer tools, and third-party integrations.

Performance Considerations

Performance is a critical aspect for any framework comparison. Generally, benchmarks for React vs Vue code examples are similar for small to medium projects. Both employ virtual DOMs for efficient UI updates. However, Vue’s reactivity system can deliver more predictable optimizations, especially in granular updates. React’s fiber architecture introduces features like concurrent rendering, ensuring smooth UI even under heavy load.

Learning Curve and Community

React’s steep learning curve comes from embracing JSX, hooks, and functional programming concepts. Documentation is extensive, and the community is unmatched in size. Vue is lauded for its gentle onboarding and exceptional documentation, making it perfect for beginners and rapid prototyping.

SEO and Server-Side Rendering

For content-heavy sites, SEO is essential. Both frameworks possess solutions: React offers Next.js, while Vue wields Nuxt.js. These meta-frameworks handle server-side rendering, static site generation, and enable deep linking—vital for discoverability in modern web applications. Developers comparing React vs Vue code examples in SSR scenarios will find equivalent, mature tooling.

Summary Table: React vs Vue Code Example Highlights

FeatureReactVue
Component FormatJSX in JSSingle-File Components
State ManagementHooks (useState, useEffect)data(), computed, methods
Event HandlingHandlers in JSXv-on / @ directive
Two-Way BindingExplicit handlerv-model
LifecycleuseEffect, class methodsmounted, updated, unmounted
StylingCSS-in-JS, external CSSScoped CSS
Community SizeHugeGrowing, passionate
Learning CurveModerate to steepGentle to moderate
SSRNext.jsNuxt.js

Choosing the Right Framework

The React vs Vue code example comparisons above reveal substantial overlap in capabilities but differing philosophies in execution. If you value an opinionated structure with flexible options, crave lightning-fast prototyping, or are newer to modern JavaScript, Vue offers an attractive path. React, with its immense ecosystem, composable nature, and unopinionated style, is ideal for developers already comfortable with JavaScript idioms and seeking maximal flexibility.

Ultimately, both frameworks shine in building modern, dynamic web experiences. The best choice depends on your project needs, team skills, and desired development velocity. By analyzing real-world use cases through React vs Vue code examples, you’re equipped to make an informed decision that best aligns with your goals.

Further Reading and Next Steps

Whether you choose React or Vue, both frameworks deliver state-of-the-art development experiences. Use these React vs Vue code examples as a starting point for experimentation, and build your next project with confidence.

More Posts