[React] Always useMemo your context value

Have a similar post about Reac.memo. This blog is the take away from this post.

 

To understand why to use 'React.useMemo' or 'React.memo' (basiclly lastest React version use 'useMemo'), is that if the function component or context create a new reference, you need to use memo. 

 

Context: 

Context provider always create a new object to the comsuers. So use memo everytime you can.

function CountProvider(props) {
  const [count, setCount] = React.useState(0)
  const value = React.useMemo(() => {
    return {
      count,
      setCount,
    }
  }, [count])
  return <CountContext.Provider value={value} {...props} />
}

 

function component:

Check the props, only do the re-render when props changes.

const TodoItem = React.memo(({ todo, onChange, onDelete }) => {
  console.log("TodoItem5", { todo, onChange, onDelete });
  const theme = useContext(ThemeContext);
  return (
    <Item key={todo.id} theme={theme}>
      <Checkbox
        id={todo.id}
        label={todo.text}
        checked={todo.completed}
        onChange={onChange.bind(this, todo.id)}
      />
      <Button onClick={onDelete.bind(this, todo.id)} theme={theme}>
        x
      </Button>
    </Item>
  );
});

 

posted @ 2019-05-07 23:49  Zhentiw  阅读(363)  评论(0编辑  收藏  举报