This version will be nicer for people who preferred old-school OOP programming. You've got the object, and you can set whatever you want there.
Example
importReact,{useState,useRef,memo}from"react";importReactDOMfrom"react-dom";import"./styles.css";constuseSelfish=(load)=>{constself=useRef(load)self.current.props=load.propsself.current.state=load.statereturn[self.current]}lettimes=0;constExpensiveComponent=memo(({onClick})=>(<ponClick={onClick}>I am expensive form component: {times++}</p>));constApp=(props)=>{const[self]=useSelfish({props:props,state:{value:useState(1)},handleClick:function(){const[value,setValue]=self.state.valuesetValue(value+1)}})const[value]=self.state.valueconsole.log("Value: "+value);return(<divclassName="app"><ExpensiveComponentonClick={self.handleClick}/><buttononClick={self.handleClick}>
I will not trigger expensive re-render
</button></div>);};constrootElement=document.getElementById("root");ReactDOM.render(<App/>,rootElement);
There is another way to go about this, maybe cleaner for some people.
It can be used like this (Try here):
This version will be nicer for people who preferred old-school OOP programming. You've got the object, and you can set whatever you want there.
Example
How can I use effect in this?
Or just with normal useEffect with dependencies [self.state.value]?
Should work fine.
But I advise you try the new, cleaner version: dev.to/anpos231/react-hooks-the-cl...