Home > other >  I'm trying to render a child component based on the data provided by the parent. Can someone ex
I'm trying to render a child component based on the data provided by the parent. Can someone ex

Time:11-19

// PARENT
const [data, setData] = useState(0);
const clickHandler = () => {
   setData(prevState => prevState   1);
}
return (
    <div>
      <RerenderCheck data={data} />
      <button onClick={clickHandler}>Click</button>
    </div>
)

// CHILD
const RerenderCheck = (props) => {
  const [count, setCount] = useState(props.data);
  return <div>{count}</div>;
};

Everything seems to work just fine except for the count in child component. I'm expecting the state "count" in child component to change whenever the parent component gets re-rendered.

const RerenderCheck = (props) => {
  return <div>{props.data}</div>;
};

This one works perfectly fine. I kind of get what's happening but would like to hear from others.

CodePudding user response:

The state will not reset when the property is updated. It is only set when the component is mounted. Just skip the state in the child.

// A state can only be updated through a setState function
// in this case setCount
const [count, setCount] = useState(0);
const clickHandler = () => {
  setData((prevState) => prevState   1);
};
return (
  <div>
    <RerenderCheck count={count} />
    <button onClick={clickHandler}>Click</button>
  </div>
);

// In the child we just pass the count as as prop
// we do not need a state here since we only want to show the count
const RerenderCheck = ({ count }) => {
  return <div>{count}</div>;
};

CodePudding user response:

The count state on the child component is being assigned props.data as its initial value. It was set during mount. When the parent updates its data state, it will re-render the child component but it will not update the count state because the only way you can update the count state is through its setter function - setCount.

If you want to update the child component's state when a prop is changed, you can use a useEffect, add the prop as dependency, and invoke the state setter function there:

const RerenderCheck = (props) => {
  const [count, setCount] = useState(props.data);

  useEffect(() => {
    setCount(props.data);
  }, [props.data]);

  return <div>{count}</div>;
};
  • Related