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

How to use with React Hooks #15

Closed
djMax opened this issue Feb 16, 2019 · 5 comments
Closed

How to use with React Hooks #15

djMax opened this issue Feb 16, 2019 · 5 comments

Comments

@djMax
Copy link

djMax commented Feb 16, 2019

I'm trying to use this component in a project which uses React Hooks, and wondering if there's a pattern that makes more sense. Here's what I have now:

function MyComponent() {
  const [logs, setLogs] = useState([]);

  useEffect(() => {
    Hook(window.console, log => {
      setLogs([...logs, Decode(log)]);
    });
  });

  return <Console logs={logs} variant="dark" />;
}

I think this is either wasteful or just wrong. The console-feed Hook will run on every render, which is why it works at all. If I make it run only once, the logs state value would not update. Any thoughts on the right pattern for this?

@samdenty
Copy link
Owner

samdenty commented Feb 16, 2019

See https://overreacted.io/making-setinterval-declarative-with-react-hooks/#second-attempt

function MyComponent() {
  const [logs, setLogs] = useState([]);

  useEffect(() => {
    Hook(window.console, log => {
      setLogs(logs => [...logs, Decode(log)]);
    });

    return () => Unhook(window.console);
  }, []);

  return <Console logs={logs} variant="dark" />;
}

@samdenty
Copy link
Owner

I'll eventually update console-feed to hooks, but haven't got round to it yet

@djMax
Copy link
Author

djMax commented Feb 16, 2019

I don't have proof yet, but I think the problem with this is that if the console.logs come in fast enough, there's no "buffering" and you will overwrite some messages that occur between renders (right?).

@samdenty
Copy link
Owner

Using the callback approach for the state updater, ensures that react can apply state updates in order

@djMax
Copy link
Author

djMax commented Feb 17, 2019

Oh - I missed that nuance, I get it now.

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