Disintegrated Parts


#software-development #web-development #react

Every now and then I have to deal with an issue where I want to pass props down to a component, handle updates to them, but at the same time want to hide the internal implementation details.

Although I might or might not be better off using a state management solution such as React Context or Redux Toolkit, I decided on still writing about this pattern as I think it has some valid use-cases. In fact, I have no idea whether I’m better off using a state management solution given I never used one. Send help.

The pattern

In order to hide the state transitions going on within a component you should keep a copy of the previous prop value, and compare it with the current prop. If these two do not match you’ll know there was a change.

import React, { useState } from 'react'

export function Component({ value, onChange }) {
  const [ _value, _setValue ] = useState()
  const [ _localValue, _setLocalValue ] = useState()

  if (_value !== value) {
    // The variable has changed externally, trigger a value change to override the local value.
    _setValue(value)
    _setLocalValue(value)
  }

  return (
    <input value={value} onChange={(e) => {
      _setLocalValue(e.target.value)
      onChange(e)
    }} />
  )
}

Although the component above has no obvious use for an internal shadow copy of a prop, it provides the boiler plate for how to implement such thing.

Use cases

Recently I had written a datetime input component for which I wanted to expose a different value than generated by the input element itself.


No webmentions were found.