Skip to content

Instantly share code, notes, and snippets.

@abernier abernier/index.md
Last active Apr 22, 2019

Embed
What would you like to do?
React cheatsheet

setState as callback function

this.setState(state => ({
  products: [...state.products, {name: 'NEW product'}]
}));

"Slots"

Also known as containment

function Popin(props) {
  return (
    <div className="Popin">
      <div className="Popin__left">
        {props.left}
      </div>
      <div className="Popin__right">
        {props.right}
      </div>
    </div>
  );
}

function App() {
  return (
    <Popin
      left={
        <Contacts />
      }
      right={
        <Chat />
      } />
  );
}

React.useState

see: https://reactjs.org/docs/hooks-reference.html#usestate

const [clicks, setClicks] = useState(0);

React.useEffect

see: https://reactjs.org/docs/hooks-reference.html#useeffect

useEffect(() => {
  // executed after any render (after render is painted to the screen)
})
const [loggedin, setLoggedin] = useState(false);

useEffect(() => {
  // executed after any render but only if `loggedin` has changed
}, [loggedin])
const [loggedin, setLoggedin] = useState(false);

useEffect(() => {
  // executed after any render but only if `loggedin` OR `props.message` has changed
}, [loggedin, props.message])
useEffect(() => {
  // executed after the first render
}, [])

cleanup

useEffect(() => {
  // 
  return () => {
    // executed before any rerender (rerender = any but not the first one)
  }
})
const [loggedin, setLoggedin] = useState(false);

useEffect(() => {
  // 
  return () => {
    // executed before any rerender but only if `loggedin` has changed
  }
}, [loggedin])

userRef

function Timer() {
  const intRef = useRef();

  useEffect(() => {
    const id = setInterval(() => {
      // ...
    });
    intRef.current = id;
    return () => {
      clearInterval(intRef.current);
    };
  });

  // ...
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.