//from
const callback = useCallback((state)=>{ setState(state.value)}, [state.value])
<Some onChange={callback(state)} /> //???
//to
const [state, setState] = useState({value: 0})
const callback = (state) => useCallback((state)=>{ setState(state.value)}, [state.value])
<Some onChange={callback} />function App() {
const refs = Array.from({ length: 2 }, a => useRef(null));
console.log(refs); //[object, object]
return (
<div className="App">
{["fafa", "eee"].map((e, i) => (
<li key={e} ref={refs[i]}>
{e}
</li>
))}
</div>
);
}// form
const [state, setState] = useState({top: 10, right: 10, bottom: 10, left: 10})
setState((state) => {...state, top:20, bottom: 5});
// if you only update this state in a whole this code, Do omit and sepalete state, you will not need marge prev state.
// to
const [state, setState] = useState({top: 10, bottom: 10})
const [stateRightLeft, setRightLeft] = useState({right: 10, left:10});
setState({top: 20, bottom: 5});const Parent = (id) => {
const fn = useCallback(()=>{ fetch("/api").then()}, [id]); //if id change, fn will be generated.
return <Child fn={fn} />
}
const Child = ({fn}) => {
useEffect(()=>{
fn()
}, [fn]) //if fn update, useEffect will be fire
}// every render
const Child = (props)=> {
useState(fn(props.value)) //and too heavy caluculate
}to
const Child = (props)=> {
useState(()=> fn(props.value)) //only once call fn at render Child
}<button onClick={(e) => this.deleteRow(id, e)}>Delete Row</button> //ok
<button onClick={this.deleteRow.bind(this, id)}>Delete Row</button> //ok// アロー関数が副作用。副作用関数。renderごとに毎回新たに作られるのでその時の更新されたstateをみれる
useEffect(() => {
console.log('effect!');
});