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

Consider if context propagation and memo gives performance improvement #2

Closed
avkonst opened this issue Jul 15, 2019 · 0 comments
Closed

Comments

@avkonst
Copy link
Owner

avkonst commented Jul 15, 2019

/* eslint-env browser */

import React from "react";
import ReactDOM from "react-dom";

const bitForA = 1 << 0;
const bitForB = 1 << 1;

const MyContext = React.createContext({ a: 1, b: 1 }, (prev, next) => {
  console.log("prev", JSON.stringify(prev));
  console.log("next", JSON.stringify(next));
  let changedBits = 0;
  if (prev.a !== next.a) changedBits |= bitForA;
  if (prev.b !== next.b) changedBits |= bitForB;
  return changedBits;
});

const ComponentA = () => {
  const context = React.useContext(MyContext, bitForA);
  return (
    <p>
      Value A: {context.a} {Math.random()}
    </p>
  );
};
const ComponentB = () => {
  const context = React.useContext(MyContext, bitForB);
  return (
    <p>
      Value B: {context.b} {Math.random()}
    </p>
  );
};

const Main = React.memo(() => (
  <React.Fragment>
    <ComponentA />
    <ComponentB />
  </React.Fragment>
));

const App = () => {
  const [state, setState] = React.useState({ a: 1, b: 1 });
  return (
    <MyContext.Provider value={state}>
      <Main />
      <button onClick={() => setState({ ...state, a: state.a + 1 })}>
        Increment A
      </button>
      <button onClick={() => setState({ ...state, b: state.b + 1 })}>
        Increment B
      </button>
    </MyContext.Provider>
  );
};

ReactDOM.unstable_createRoot(document.getElementById("app")).render(<App />);
@avkonst avkonst closed this as completed Aug 15, 2019
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

1 participant