useContext() 不应该只用于低频率更新吗? (mobx-react-lite)

Shouldn't useContext() only be used for low frequent updates? (mobx-react-lite)

几乎所有示例(甚至官方文档)都使用 mobx-react-light 结合 useContext() 钩子。

但是,React、许多文章和博客文章建议 不要使用 useContext() 进行 middle/high 频繁更新。状态不是可以更新很频繁的东西吗?

是否应该将包与挂钩结合使用,否则会出现性能问题吗?

useContext()只是用来获取你的店铺值(参考),这个值不会经常更新,一般你只设置一次店铺,之后就不要再碰了。当您使用操作时,您只会更改商店的可观察值,而不是商店本身。所以基本上 Context 仅用于将引用传递到树下的商店,之后所有工作仅由 MobX 执行。

来自 MobX 文档的示例:

import {observer} from 'mobx-react-lite'
import {createContext, useContext} from "react"

const TimerContext = createContext<Timer>()

const TimerView = observer(() => {
    // Grab the timer from the context.
    const timer = useContext(TimerContext) // See the Timer definition above.
    return (
        <span>Seconds passed: {timer.secondsPassed}</span>
    )
})

ReactDOM.render(
    <TimerContext.Provider value={new Timer()}
        <TimerView />
    </TimerContext.Provider>,
    document.body
)

因此,当您呈现您的应用程序时,您将 new Timer() 的值传递给 TimerContext.Provider 一次,此后它将永远不会更改或更新。甚至文档说:

Note that we don't recommend ever replacing the value of a Provider with a different one. Using MobX, there should be no need for that, since the observable that is shared can be updated itself.

但是,如果您没有 SSR 或者不测试您的应用程序,那么您甚至根本不需要使用 Context,您可以只使用全局 variables/singletons 作为您的商店,它将工作得很好。

示例:

// Initialize timer somewhere
export const myTimer = new Timer()

// You can use directly in the same file or import somewhere else
import { myTimer } from './file-with-your-timer'

// No props, `myTimer` is directly consumed from the closure or from another file
const TimerView = observer(() => <span>Seconds passed: {myTimer.secondsPassed}</span>)

ReactDOM.render(<TimerView />, document.body)

引自文档:

Using observables directly works very well, but since this typically introduces module state, this pattern might complicate unit testing. Instead, we recommend using React Context instead.

有关 React 最佳实践的更多信息:https://mobx.js.org/react-integration.html