Skip to content

Instantly share code, notes, and snippets.

@kenmori
Last active May 17, 2019 00:42
Show Gist options
  • Save kenmori/f09d6ce2f89e77acc5da88097c79d944 to your computer and use it in GitHub Desktop.
Save kenmori/f09d6ce2f89e77acc5da88097c79d944 to your computer and use it in GitHub Desktop.
ReactHooks Tips

ReactHooksTips

callback

//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} />

refs will be attatch maped element

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>
  );
}

omit marge prev state

// 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});

dependency manage

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
}

expensive initialState

// 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
}

see

pass event and other

<button onClick={(e) => this.deleteRow(id, e)}>Delete Row</button> //ok
<button onClick={this.deleteRow.bind(this, id)}>Delete Row</button> //ok

effect

// アロー関数が副作用。副作用関数。renderごとに毎回新たに作られるのでその時の更新されたstateをみれる
  useEffect(() => {
    console.log('effect!');
  });

twitter

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment