DEV Community

Cover image for A Simple Way to Expose Internal Component State in React
Aneesh
Aneesh

Posted on

A Simple Way to Expose Internal Component State in React

Consider a scenario where you have a DatePicker component with its internal state, and you want to provide a way for external components to access this state. This can be achieved by creating a callback function, often referred to as a prop, to allow external components to interact with the DatePicker. Here's an example:

const DatePicker = ({ maxDate = maxDateValue, log = true, consumeDate = () => {} }) => {
  const [value, setValue] = React.useState(() => {
    consumeDate(new Date()); // Expose the initial value
    return new Date();
  });
  if (log) console.log('Date picker value...', value);

  return (
    <Container>
      <Calendar
        value={value}
        onChange={(vl) => {
          setValue(vl);
          consumeDate(vl); // Expose the updated value
        }}
        minDate={new Date()}
        maxDate={maxDate}
      />
    </Container>
  );
};
Enter fullscreen mode Exit fullscreen mode

In this example, the DatePicker component provides a consumeDate prop that external components can use to access the internal state of the component. This approach facilitates sharing the component's state and opens the door to numerous possibilities.

Here's how this works:

The consumeDate prop is passed to the DatePicker component, which is a function that can be defined in any parent component.

Inside the DatePicker component, this function is called during initialization and whenever the date value changes. This allows external components to observe the initial and updated values.

The onChange event of the Calendar component triggers the update of the internal state (value) in the DatePicker. It also calls consumeDate, exposing the new value.

Top comments (0)