Vue vs React: Quick Guide to Single‑File, Class, and Functional Components

This article compares Vue’s single‑file components with React’s class and functional components, explains the shift from two‑way binding to one‑way data flow, introduces JSX and React Hooks, discusses state‑management patterns like Vuex and Redux, and provides a practical TodoList implementation.

Alibaba Cloud Developer
Alibaba Cloud Developer
Alibaba Cloud Developer
Vue vs React: Quick Guide to Single‑File, Class, and Functional Components

Vue Single‑File Component

Vue uses a single‑file component format that combines template, script, and style sections.

<template>
  <div>{{ greeting }} world</div>
</template>

<script>
export default {
  data() {
    return {
      greeting: 'hello'
    }
  }
}
</script>

<style>
</style>

React Class Component

React class components extend Component and manage state via this.state and this.setState.

class Comp extends Component {
  constructor(props) {
    super(props);
    this.state = { greeting: 'hello' };
  }

  render() {
    return (
      <div>
        <div>{ greeting } world</div>
      </div>
    );
  }
}

React Functional Component (Hooks)

Functional components use Hooks such as useState for state handling, offering a simpler syntax.

const Comp = () => {
  const [greeting, setGreeting] = useState('hello');

  return (
    <div>
      <div>{ greeting } world</div>
    </div>
  );
};

Two‑Way Binding vs One‑Way Data Flow

Vue’s v-bind and v-model enable two‑way binding, automatically updating data on user interaction. React requires explicit state updates via setState or Hook setters, making data changes more traceable.

// Vue two‑way binding example
this.data.greeting = "Hello";

// React state update (correct)
this.setState({ greeting: "Hello" }); // ✅
// Hook update
setGreeting('Hello'); // from useState

JSX in React

JSX mixes HTML‑like markup with JavaScript expressions, allowing conditional rendering and inline logic.

import getUserType from './getUserType';

const Comp = () => {
  const [greeting, setGreeting] = useState('hello');

  const Button = () => {
    const userType = getUserType();
    if (userType === 0) return <button>去购买</button>;
    if (userType === 1) return <button>去充值</button>;
    return null;
  };

  return (
    <div>
      <div>{ greeting } world</div>
      {Button()}
    </div>
  );
};

Hooks Overview

useState defines component state, similar to Vue’s data or this.state in class components.

const [greeting, setGreeting] = useState('hello'); // default "hello"
// Example: change greeting on click
<div onClick={() => setGreeting('Hello1')}>{greeting}</div>

useEffect runs side effects based on dependency changes, comparable to Vue’s watcher.

// Run when userId changes
useEffect(() => {
  refresh();
}, [userId]);

// Run on mount and cleanup on unmount
useEffect(() => {
  init();
  return () => {
    destroy();
  };
}, []);

useRef provides a mutable ref object to access DOM elements directly.

const el = useRef(null);
<div ref={el}></div>
// console.log(el.current.offsetHeight);

State Management

Centralized state stores keep component data predictable. Vue uses Vuex; React relies on third‑party libraries such as Redux, MobX, or Rax.

When a store is introduced, components read directly from it and invoke store methods to modify data, eliminating prop‑drilling.

Vuex Example

import { createStore } from 'vuex';

const store = createStore({
  state: { count: 0 },
  mutations: {
    setCount(state, value) { state.count = value; }
  },
  actions: {
    addon({ commit, state }) {
      const count = state.count;
      commit('setCount', count + 1);
    }
  }
});

React (Rax) Example

export default {
  state: { count: 0 },
  reducers: {
    increment(prevState) { return { count: prevState.count + 1 }; }
  },
  effects: (dispatch) => ({
    async incrementAsync() {
      await delay(10);
      dispatch.counter.increment();
    }
  })
};

import { createStore } from 'rax-app';
import counter from './models/counter';
const store = createStore({ counter });

export default function Dashboard() {
  const [counterState, counterDispatchers] = store.useModel('counter');
  return (
    <>
      <span>{counterState.count}</span>
      <button onClick={counterDispatchers.increment}>+</button>
      <button onClick={counterDispatchers.incrementAsync}>+</button>
    </>
  );
}

React TodoList Practical Example

The following snippet shows a TodoList built with React, Redux‑style state handling, and Ant Design‑like UI components.

import React, { useCallback } from 'react';
import { connect } from 'react-redux';
import { Link } from '@ice/router';
import { Form, Input } from 'cn-next';

const AddTodo = ({ onAdd }) => {
  const onSubmit = useCallback((values, errors) => {
    if (!errors) onAdd(values.text);
  }, [onAdd]);

  return (
    <div>
      <Form inline onSubmit={onSubmit}>
        <Form.Item requiredMessage="请输入待办事项">
          <Input name="text" placeholder="请输入待办事项" />
        </Form.Item>
        <Form.Submit>添加</Form.Submit>
      </Form>
    </div>
  );
};

const Todos = ({ list, createAsync }) => {
  const onAddTodo = useCallback(async (text) => {
    await createAsync(text);
  }, [createAsync]);

  return (
    <div>
      <AddTodo onAdd={onAddTodo} />
      <div>{list.map(item => <div key={item.text}>{item.text}</div>)}</div>
      <Link to="/">返回首页</Link>
    </div>
  );
};

const mapState = state => ({ list: state.todos.list });
const mapDispatch = dispatch => ({
  createAsync: dispatch.todos.createAsync,
  doneAsync: dispatch.todos.doneAsync,
  undoneAsync: dispatch.todos.undoneAsync,
});

export default connect(mapState, mapDispatch)(Todos);

These examples illustrate how Vue developers can transition to React by understanding component syntax, data flow, JSX, Hooks, and state‑management solutions.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

frontendState ManagementReacthooksJSX
Alibaba Cloud Developer
Written by

Alibaba Cloud Developer

Alibaba's official tech channel, featuring all of its technology innovations.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.