Skip to content

Instantly share code, notes, and snippets.

@cocodrino
Created September 1, 2022 00:35
Show Gist options
  • Save cocodrino/0a60427c4a152c389fcac07598a65dac to your computer and use it in GitHub Desktop.
Save cocodrino/0a60427c4a152c389fcac07598a65dac to your computer and use it in GitHub Desktop.
same ReactJS incremental counter in functional style using HOC,render props and Hooks
import React,{useEffect,useState} from "react";
const useCounter=()=>{
const [count,setCount] = useState(0)
useEffect(()=>{
let timer = setInterval(()=>{setCount(v=>v+10)},2000)
return ()=>{clearInterval(timer)}
},[])
return [count]
}
const MessageUpdatedWithHook = ()=>{
const [count] = useCounter()
return(<Message message={count} color="red"/>)
}
const withHigherOrderComponent = (Component) => (props) => {
const [count,setCount] = useState(0)
useEffect(()=>{
let timer = setInterval(()=>{setCount(v=>v+1)},2000)
return ()=>{clearInterval(timer)}
},[])
return(
<Component message={count} {...props} />
)
}
const WithRenderProps = (props)=>{
const [count,setCount] = useState(0)
useEffect(()=>{
let timer = setInterval(()=>{setCount(v=>v+1)},2000)
return ()=>{clearInterval(timer)}
},[])
return(
<div>
{props.render(count)}
</div>
)
}
const Message = (props)=>{
const {message,color} = props
return(
<div style={{color}}>
{message}
</div>
)
}
const Sample = (props)=>{
const WithHOC = withHigherOrderComponent(Message)
return(
<div>
<MessageUpdatedWithHook/>
<WithHOC color="green"/>
<WithRenderProps render={(v)=><Message message={v} color="gray" />}/>
</div>
)
}
export default function App() {
return (
<div className="App">
<h1>Incremental counter implemented in HOC,render props and Hooks</h1>
<Sample/>
<h2>Cocodrino</h2>
</div>
);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment