Implementing Computed Properties in React: From Class Methods to Hooks and Memoization
This article explains how to emulate Vue's computed properties in React by extracting calculations from the render method, using class getters, applying memoization with memoize-one, and leveraging the useMemo hook to achieve dependency‑based caching and cleaner component code.
In Vue, computed properties are declaratively defined and cached based on reactive dependencies, while in React similar logic is often placed directly in the render method, making it bulky.
Example of a React class component that builds fullName inside render by concatenating firstName and lastName from state.
import React, { Fragment, Component } from 'react';
class Example extends Component {
state = { firstName: '', lastName: '' };
render() {
const { firstName, lastName } = this.state;
const fullName = `${firstName} ${lastName}`;
return
{fullName}
;
}
}To avoid clutter, the computation can be extracted into a helper method.
class Example extends Component {
// ...
renderFullName() {
const { firstName, lastName } = this.state;
return `${firstName} ${lastName}`;
}
render() {
const fullName = this.renderFullName();
return
{fullName}
;
}
}React also supports getters, but they do not provide caching.
class Example extends Component {
get fullName() {
const { firstName, lastName } = this.state;
return `${firstName} ${lastName}`;
}
render() {
return
{this.fullName}
;
}
}Memoization can be added with the memoize-one library to achieve Vue‑like caching.
import memoize from 'memoize-one';
class Example extends Component {
getFullName = memoize((firstName, lastName) => `${firstName} ${lastName}`);
get fullName() {
return this.getFullName(this.state.firstName, this.state.lastName);
}
// render ...
}With React Hooks, the same effect is expressed using useMemo , which recomputes only when its dependency array changes.
import React, { useState, useMemo } from 'react';
function Example() {
const [firstName, setFirstName] = useState('');
const [lastName, setLastName] = useState('');
const renderFullName = useMemo(() => `${firstName} ${lastName}`, [firstName, lastName]);
return
{renderFullName}
;
}The article concludes that although React lacks a native computed API, the ecosystem provides patterns—helper methods, getters, memoization libraries, and hooks—to keep render logic clean and performant.
政采云技术
ZCY Technology Team (Zero), based in Hangzhou, is a growth-oriented team passionate about technology and craftsmanship. With around 500 members, we are building comprehensive engineering, project management, and talent development systems. We are committed to innovation and creating a cloud service ecosystem for government and enterprise procurement. We look forward to your joining us.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.