samdenty / console-feed

Captures console.log's into a React Component 🔥
https://stackblitz.com/~/github.com/samdenty/console-feed
MIT License
670 stars 109 forks source link

How to use with React Hooks #15

Closed djMax closed 5 years ago

djMax commented 5 years ago

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 commented 5 years ago

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 commented 5 years ago

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

djMax commented 5 years ago

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 commented 5 years ago

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

djMax commented 5 years ago

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