Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

createContext 的第二个参数优化更新的用法要被移除了 #4

Closed
mysteryven opened this issue Dec 11, 2021 · 7 comments
Closed

Comments

@mysteryven
Copy link

mysteryven commented Dec 11, 2021

const Context = React.createContext<Value | null>(null, () => 0);

React 有一个 PR ,现在已经把这种用法移除掉了。

可能我想得不够全面,但是感觉这里采用下面的写法就足够了:

 const value = useMemo(() => {
    return useHook(initialState);
  }, [useHook])
@MinJieLiu
Copy link
Owner

这里目前只是为了少点代码,其实想实现这种效果很简单,用 ref 转发一下就够了,我后面改一下

@MinJieLiu
Copy link
Owner

你下面那种写法不行的,会破坏 hooks 的限制

@mysteryven
Copy link
Author

你下面那种写法不行的,会破坏 hooks 的限制

破坏限制具体指的什么呢?可否赐教一下。

我目前的理解是,只要后面 value 一直不变,就都不会触发 context 的穿透更新。而使用 useMemo 包了一层就保证了这件事。毕竟 useHook 这个参数在调用 createStore 之后就不会改变了

@MinJieLiu
Copy link
Owner

@MinJieLiu
Copy link
Owner

useHook 本质是一个自定义 hook

@MinJieLiu
Copy link
Owner

@mysteryven 6d4ae85

@mysteryven
Copy link
Author

@mysteryven 6d4ae85

看完了,很 nice

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants