2

It's a kinda silly question but can I use useCallback and useMemo in React class (or equivalent solution)? Is it a good practice?

The workaround I found is to use a package named Memoizee: https://www.npmjs.com/package/memoizee. However, this is a 3rd package (is there any React built-in solution?)

Since my old component is React class, it will take a pretty amount of time to convert it to React Hooks

3
  • @ori-drori No it's not a duplicate, My question is how can I memoize values, (or functions) in React class? All articles on the net are about memoizing in React Hooks Commented Dec 14, 2019 at 20:00
  • Your wording specifically says useCallback and useMemo, so it's a bit misleading. You should change the question, and add some code that you tried. Unless you want to get voted down, and get the question closes for other reasons. However, there're lots of hookless memoize in react questions/answers around. Commented Dec 14, 2019 at 20:06
  • I change the title, I think it is clear enough now Commented Dec 14, 2019 at 20:12

1 Answer 1

1

For useCallback it's pretty easy to get. With class properties syntax(to store value between renders) and arrow function expression(to bind this) you can do that:

 onClick = (e) => { this.setState({ clicked: true }); }
...
 render() {
   ...
   <button onClick={this.onClick}

And sure, you can just do that in constructor, if don't want to include babel plugin to support class properties:

 constructor() {
   this.onClick = this.onClick.bind(this);
 }

 onClick(e) {
   this.setState({ clicked: true });
 }

As for useMemo you may utilize any existing package for that, say lodash's _.memoize.

Just to highlight: useMemo hook is rather for preserving referential equality (say, if some function returns an array or an object than calling that function on each render would provide referentially different result on each run). So as alternative to memoization you may just check if some dependencies have been changed in componentDidUpdate and once they did - calculate some new data and, say, write it to state or directly to this(say, if that's timed ID returned from setTimeouer)

Sign up to request clarification or add additional context in comments.

1 Comment

It's very helpful

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.