首页 > web前端 > js教程 > 正文

React: State X Derived State

Linda Hamilton
发布: 2024-09-24 08:30:10
原创
231 人浏览过

React: State X Derived State

What’s a derived state? Think one state for text and then another for uppercaseText.

Derived State

function Foo() {
    const [text, setText] = useState('hello, za warudo!');
    const [uppercaseText, setUppercaseText] = useState(text.toUpperCase());

    useEffect(() => {
        setUppercaseText(text.toUpperCase());
    }, [text])

    ...
}
登录后复制

Putting like that it’s crazy to think anyone would do this… right? RIGHT?

Yes, an example like this will make clear that this is wrong.

The Bad of Derived State

  • Stored separately and out-of-sync with the actual state.
  • Triggers (depend) on unnecessary re-renders.

How to refactor the derived state?

Say it’s an expensive calculation… the solution is to use useMemo.

function Foo() {
    const [text, setText] = useState('hello, za warudo!');
    const uppercaseText = useMemo(() => text.toUpperCase(), [text]);
    ...
}
登录后复制

How to quickly spot state that can be derived?

I came up with a good way of thinking that should make it easier to KNOW if a state should be “another state” or just a computed property (memorized or not depending on the case).

function Foo({
    text = 'hello, za warudo!',
    uppercaseText = text.toUpperCase(),
}) {
    ...
}

// Forget react for a moment...
// Would you ever call a function like this?
const text = 'hello, za warudo!';
Foo({
    text,
    uppercaseText: text.toUpperCase(),
});
登录后复制

If you think of those states as “props”, then this makes it more blatantly what it should be.

Forget React entirely, think only of functions:
Would you call a function with a variable and then another variable you could just compute inside?

以上是React: State X Derived State的详细内容。更多信息请关注PHP中文网其他相关文章!

来源:dev.to
本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
作者最新文章
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责声明 Sitemap
PHP中文网:公益在线PHP培训,帮助PHP学习者快速成长!