Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using state setter as prop with react hooks

I'm trying to understand if passing the setter from useState is an issue or not.

In this example, my child component receives both the state and the setter to change it.

export const Search = () => {
  const [keywords, setKeywords] = useState('');

  return (
    <Fragment>
      <KeywordFilter
        keywords={keywords}
        setKeywords={setKeywords}
      />
    </Fragment>
  );
};

then on the child I have something like:

export const KeywordFilter: ({ keywords, setKeywords }) => {

  const handleSearch = (newKeywords) => {
    setKeywords(newKeywords)
  };

  return (
    <div>
      <span>{keywords}</span>
      <input value={keywords} onChange={handleSearch} />
    </div>
  );
};

My question is, should I have a callback function on the parent to setKeywords or is it ok to pass setKeywords and call it from the child?

like image 763
mgcs Avatar asked Sep 24 '19 16:09

mgcs


People also ask

How do you pass state props in React Hooks?

First, click on App and observe its state under the Hooks section on the right pane. Second, click on a given player component and examine its props. Finally, click on any of the items in the page and see how the state and props of the parent and child components are updated, respectively.

Can we pass state as props in React?

To pass the state into another component, you can pass it as a prop.

Should I use state or props React?

For parent-child communication, simply pass props. Use state to store the data your current page needs in your controller-view. Use props to pass data & event handlers down to your child components. These lists should help guide you when working with data in your components.

Can you setState with props?

The setState() MethodState can be updated in response to event handlers, server responses, or prop changes. This is done using the setState() method. The setState() method enqueues all of the updates made to the component state and instructs React to re-render the component and its children with the updated state.


1 Answers

There's no need to create an addition function just to forward values to setKeywords, unless you want to do something with those values before hand. For example, maybe you're paranoid that the child components might send you bad data, you could do:

const [keywords, setKeywords] = useState('');

const gatedSetKeywords = useCallback((value) => {
  if (typeof value !== 'string') {
    console.error('Alex, you wrote another bug!');
    return;
  }
  setKeywords(value);
}, []);

// ...

<KeywordFilter
  keywords={keywords}
  setKeywords={gatedSetKeywords}
/>

But most of the time you won't need to do anything like that, so passing setKeywords itself is fine.

like image 129
Nicholas Tower Avatar answered Sep 27 '22 18:09

Nicholas Tower