Skip to content

Instantly share code, notes, and snippets.

@igrek8
Last active May 6, 2019 15:15
Show Gist options
  • Select an option

  • Save igrek8/1428e7483bf60a1c60972763e11fcecc to your computer and use it in GitHub Desktop.

Select an option

Save igrek8/1428e7483bf60a1c60972763e11fcecc to your computer and use it in GitHub Desktop.
Prevent useCallback rerendering children components https://codesandbox.io/embed/o5o3znl656
import React, { useState, useRef, useCallback } from "react";
import Button from "./Button";
function App() {
const [state, setState] = useState("");
const ref = useRef(state);
const handleChange = useCallback(event => {
ref.current = event.target.value;
setState(event.target.value);
}, []);
const handleClick = useCallback(
event => {
event.preventDefault();
alert(ref.current);
},
[ref]
);
return (
<form onSubmit={handleClick}>
<input onChange={handleChange} />
<Button onClick={handleClick} />
</form>
);
}
export default App;
import React, { useRef } from "react";
const Button = ({ onClick }) => {
const counter = useRef(0);
return <button onClick={onClick}>Click me {counter.current++}</button>;
};
export default React.memo(Button);
import { useRef, useState, useCallback } from "react";
function useMemoState(...args) {
const [state, _setState] = useState(...args);
const memoState = useRef(state);
const setState = useCallback(
nextState => {
memoState.current = nextState;
_setState(nextState);
},
[memoState]
);
return [memoState, setState];
}
export default useMemoState;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment