DEV Community

Hatem Houssein
Hatem Houssein

Posted on • Edited on

1

React hooks vs Meteor reactive var

I have been working heavily with MeteorJS, so Reactive-var has become almost a second-nature to me and I assume you have a good understanding of how templating and Reactive vars run in Meteor. Meanwhile, I have been working with React more often lately. Now, it's been roughly 5 months since React Hooks has been out at the time of writing this. I was reading the Hooks docs then watched a video by MPJ with Dan who works at React. I recommend the video (it's 30 min. long if you watch in 2x speed 😉)

So let's jump to code to see how different/similar React Hooks work compared to Meteor's Reactive-var.

Meteor version of a simple Reactive var create/get/set.

import { Template } from 'meteor/templating';
import { ReactiveVar } from 'meteor/reactive-var';

import './my_cool_text_field.html';

const template = Template.my_cool_text_field;

template.onCreated(() => {
  const instance = Template.instance();
  // Suppose we have a text input field called "title"
  instance.titleVar = new ReactiveVar('');
});

template.helpers({
  getTitle() {
    return Template.instance().titleVar.get();
  }
});

template.events({
  'click .change-title': () => Template.instance().titleVar.set(newTitle)
});
Enter fullscreen mode Exit fullscreen mode

React version of the same Meteor processes

import React, { useState } from 'react';

export default MyCoolTextField = () => {
  // `useState()` returns the variable and a setter function for the variable
  // We set the default value of `title` as a parameter to `useState()`
  const [title, setTitle] = useState('');

  const handleChange = event => setTitle(event.target.value);

  return (
    <div>
      <input
        className="change-title"
        name="title"
        type="text"
        value={title}
        onChange={handleChange}
      />
    </div>
  );
};
Enter fullscreen mode Exit fullscreen mode

Also note the I haven't put the template HTML for the Meteor snippet.

Qodo Takeover

Introducing Qodo Gen 1.0: Transform Your Workflow with Agentic AI

Rather than just generating snippets, our agents understand your entire project context, can make decisions, use tools, and carry out tasks autonomously.

Read full post →

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay