Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

avoid useEffect to render at first load?

I know useEffect is the 'combination' of componentDidUpdate and componentDidMount? but since I have already passed in a dependency, why is it still load during the first load?

import React, { useState, useEffect } from "react";
import { Button, Table, Column } from "antd";

const initData = [
  {
    id: 1,
    name: "James"
  },
  {
    id: 2,
    name: "John"
  }
];

function MyTable({ changeDataFlag }) {
  const [data, setData] = useState(initData);

  useEffect(() => {
    setData(
      data.map(o => ({
        id: "Titus",
        name: "Paul"
      }))
    );
  }, [changeDataFlag]);

  return (
    <Table dataSource={data} rowKey={data => data.id}>
      <Column title="Id" dataIndex="id" />
      <Column title="Name" dataIndex="name" />
    </Table>
  );
}

export default MyTable;

I expect to see James and John on the table before I click update button

https://codesandbox.io/s/hello-antd-t29cs

like image 295
Hanz Avatar asked Jun 27 '26 19:06

Hanz


1 Answers

By default useEffect run first time and then on change of dependencies.

You can do this,

useEffect(() => {
    if(changeDataFlag){
      setData(
        data.map(o => ({
          id: "Titus",
          name: "Paul"
        }))
      );
    }
}, [changeDataFlag]);
like image 163
ravibagul91 Avatar answered Jun 29 '26 10:06

ravibagul91



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!