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

[Suggestion]: Document: How use(Context) work with React.memo #7358

Open
dislido opened this issue Dec 12, 2024 · 0 comments
Open

[Suggestion]: Document: How use(Context) work with React.memo #7358

dislido opened this issue Dec 12, 2024 · 0 comments

Comments

@dislido
Copy link

dislido commented Dec 12, 2024

Summary

When the context value changes, React will re-render the components using 'useContext(Context)'.
'use(Context)' can be called conditionally, the memorized components will be updated only when 'use(Context)' is called in the last rendering.

Page

https://react.dev/reference/react/use#reading-context-with-use

Details

A bad example (This behavior does not seem to cause any problems in common usage)

import React, { useState, useContext, use, useRef } from "react";

const MyContext = React.createContext({ value: 1 });

const CompUseCtx = React.memo(() => {
  const { value } = useContext(MyContext);
  return <div>useContext value {value}</div>;
});

const RandomUseContext = React.memo(() => {
  const renderCount = useRef(0);
  renderCount.current++;
  if (Math.random() > 0.3) {
    const { value } = use(MyContext);
    return (
      <div>
        use value {value} renderCount {renderCount.current}
      </div>
    );
  }
  return <div>renderCount {renderCount.current}</div>;
});

export default function App() {
  const [value, setValue] = useState(1);
  return (
    <MyContext.Provider value={{ value }}>
      value: {value}
      <button onClick={() => setValue((prev) => prev + 1)}>+1</button>
      <CompUseCtx />
      <RandomUseContext />
    </MyContext.Provider>
  );
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant