Curls, clouds and code

Hi, my name is Corstian, and this is my blog where I get to publish my writings on topics such as psychology, philosophy, software development and any other thing I deem worthy to write about.

Hiding React component props within a shadow state

Published on the
software development

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.


Share this post:


Subscribe for more goodness!

👉 Do you like what I'm writing? Sign up to receive new content straight into your mailbox!