From ef0b3b773df0acc2bfbd2ad552830054dfbb895d Mon Sep 17 00:00:00 2001 From: Dan Abramov Date: Tue, 5 Jun 2018 23:46:23 +0100 Subject: [PATCH] Explain memoization --- content/blog/2018-06-07-when-to-use-derived-state.md | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/content/blog/2018-06-07-when-to-use-derived-state.md b/content/blog/2018-06-07-when-to-use-derived-state.md index 77f30be41..75900c238 100644 --- a/content/blog/2018-06-07-when-to-use-derived-state.md +++ b/content/blog/2018-06-07-when-to-use-derived-state.md @@ -236,7 +236,9 @@ For **uncontrolled** components, if you're trying to **"reset" one or more state ## What about memoization? -Another thing we've seen derived state used for is memoization. This isn't necessarily bad, but there are reasons you may want to avoid it. Hopefully the above examples illustrate that there is a certain amount of complexity inherent in using `getDerivedStateFromProps`. This complexity increases with each derived property. For example, if we add a second derived field to our component state then our implementation would need to separately track changes to both: +We've also seen derived state used to ensure an expensive value is recomputed only when the inputs change. This technique is known as [memoization](https://en.wikipedia.org/wiki/Memoization). + +Using derived state for memoization isn't necessarily bad, but there are reasons you may want to avoid it. Hopefully the above examples illustrate that there is a certain amount of complexity inherent in using `getDerivedStateFromProps`. This complexity increases with each derived property. For example, if we add a second derived field to our component state then our implementation would need to separately track changes to both: ```js class Example extends Component { @@ -381,4 +383,4 @@ There are a couple of constraints to consider when using memoization though: The examples above are intentionally simplified in order to highlight specific coding patterns. In real world applications, components often contain a mix of controlled and uncontrolled behaviors. This is okay! Just be careful to ensure that each behavior has a clear source of truth in order to avoid the anti-patterns mentioned above. -If you have a use case that you think falls outside of these patterns, please share it with us on [GitHub](https://github.com/reactjs/reactjs.org/issues/new) or Twitter! \ No newline at end of file +If you have a use case that you think falls outside of these patterns, please share it with us on [GitHub](https://github.com/reactjs/reactjs.org/issues/new) or Twitter!