Skip to content

Instantly share code, notes, and snippets.

View johnloven's full-sized avatar

John Lovén johnloven

View GitHub Profile
import { useRef, useEffect, useCallback } from "react";
// Rate limit a function but make sure the last call in a series of calls is run.
function useRateLimitedCallback(timeout, callback) {
// Save the callback in a ref to allow using a un-memoized callback parameter without changing identity of the returned callback function
const callbackRef = useRef(callback);
useEffect(() => {
callbackRef.current = callback;
});
const injectFunc = WrappedComponent =>
class InjectFunc extends React.Component {
render() {
return <WrappedComponent func={this.log} {...this.props}/>;
}
log = () => console.log("This function is from the HOC!");
}
@injectText
class MyPage extends React.Component {
render() {
console.log(this.props.text); // Will write "This text is from the HOC!" to console.
return <SomeContent/>;
}
}
const injectText = WrappedComponent =>
class InjectText extends React.Component {
return <WrappedComponent text="This text is from the HOC!" {...this.props}/>;
}
@doNothing
class MyPage extends React.Component {
render() {
return <SomeContent/>;
}
}
const doNothing = WrappedComponent =>
class DoNothing extends React.Component {
render() {
return <WrappedComponent {...this.props}/>
}
};
export default doNothing;
class App extends React.Component {
render() {
return (
<div>
<StudentPage/>
<OtherPage/>
<AndOtherPage}/>
<div>
);
}
class App extends React.Component {
render() {
return (
<div>
<DataContainer component={StudentPage} fetchData={() => fetch("myschool/student")}/>
<DataContainer component={OtherPage} fetchData={() => fetch("myschool/other")}/>
<DataContainer component={AndOtherPage} fetchData={() => fetch(("myschool/andanother")}/>
<div>
);
}
class App extends React.Component {
render() {
return (
<div>
<StudentContainer/>
<OtherContainer/>
<AndAnotherContainer/>
<div>
);
}