Created
January 7, 2016 02:38
-
-
Save mheiber/0e51bbf8585c9fc548b9 to your computer and use it in GitHub Desktop.
Memoizing React stateless function components
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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')); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<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