Closed djMax closed 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" />;
}
I'll eventually update console-feed to hooks, but haven't got round to it yet
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?).
Using the callback approach for the state updater, ensures that react can apply state updates in order
Oh - I missed that nuance, I get it now.
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:
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?