facebook / react

The library for web and native user interfaces.
https://react.dev
MIT License
228.69k stars 46.81k forks source link

Antipattern? Pass state dispatcher as a prop to child component #16043

Closed vyushin closed 5 years ago

vyushin commented 5 years ago

Do you want to request a feature or report a bug?

I have question

Can I pass state dispatcher (second arg from useState) as a prop to child component. Is it antipattern or allowable practice?

For example. I have a component TextField. I'm using it everywhere. And everyvere I need save its value to state. For example:

import { default as React, setState, useCallback } from 'react';
import { TextField } from '@component';

const SomeComponent = (props) => {
  const [value, setValue] = useState('');

 const handleChange = useCallback((e) => setValue(e.target.value), []);

  return (
    <div>
      <TextField onChange={handleChange} />
    </div>
  )
}

I'm tired to write handleChange everywhere when TextField had used... I want make this case simpliest.

Can I pass setValue to TextField as a props (instead adding onChange) and implement setting value inside of TextField?

// ...
  <TextField valueDispatcher={setValue} />
//...
dmytro-lymarenko commented 5 years ago

As of this section https://reactjs.org/docs/hooks-faq.html#how-to-avoid-passing-callbacks-down I think it is ok to pass down setState from useState as this function is similar to dispatch from useReducer.

vyushin commented 5 years ago

@dmytro-lymarenko, nice! Looks like real proof that it isn't antipattern)