Search code examples
reactjsreact-statereact-state-management

I'm trying to render a child component based on the data provided by the parent. Can someone explain me what's happening here?


// 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.


Solution

  • 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>;
    };