Skip to content

Instantly share code, notes, and snippets.

@mheiber
Created January 7, 2016 02:38
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mheiber/0e51bbf8585c9fc548b9 to your computer and use it in GitHub Desktop.
Save mheiber/0e51bbf8585c9fc548b9 to your computer and use it in GitHub Desktop.
Memoizing React stateless function components
import React from 'react';
import {render} from 'react-dom';
import memoize from 'memoization';
const Foo = ({number}) => {
console.log(`Rendering with number= ${number}`);
return <div>{number}</div>
};
// `memoize` caches the return value of a function.
// When the function is called multiple times
// with the same arguments, the cached return value
// is used instead of calling the original function
const MemoizedFoo = memoize(Foo);
// Logs this to the console:
// Rendering with number=1
// Rendering with number=2
// Rendering with number=3
// Caches the result of rendering number=1!
const App = ()=> (
<div>
<MemoizedFoo number={1} />
<MemoizedFoo number={2} />
{/* Rendering this element into the DOM
doesn't log anything to the console,
since the result of `Foo({number: 1})`
is cached by the `memoize` function.
*/}
<MemoizedFoo number={1} />
<MemoizedFoo number={3} />
</div>
);
render(<App/>, document.querySelector('#react'));
<div id="react"></div>
<script src="bundle.js"></script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment