DEV Community

Discussion on: How to build a search bar in React

Collapse
 
emma profile image
Emma Goto 🍙

Hi, thanks for the feedback - do you have suggestions on how you would approach this instead?

Collapse
 
faiwer profile image
Stepan Zubashev

Mydrax:

const [searchValue, setSearchValue] = useState('');

// 1
return <SearchInput onChange={setSearchValue}/>

// 2
const onChange = (newValue: string) => {
  setSearchValue(newValue);
};

return <SearchInput onChange={setSearchValue}/>;
Enter fullscreen mode Exit fullscreen mode

Do you mean this? I think it's just another one level of bureaucracy. The only difference is that you cannot do this with the wrapper:

onChange(prevValue => ...)
Enter fullscreen mode Exit fullscreen mode

But if you use TypeScript and will declare prop-type like:

onChange: (newValue: stirng): void
Enter fullscreen mode Exit fullscreen mode

you would not be able to do it anyway

I think it's more than "okay" to pass setters below the tree. And it doesn't violate top-down principle. The parent component in both cases is the only source of truth. And the only way to change the state is to use those tools that parent components provide to its children.

P.S. also if you're interested in strong performance you will wrap you wrapper by another wrapper (useCallback) :)

Collapse
 
wannabehexagon profile image
ItsThatHexagonGuy • Edited

First off what you did wasn't wrong, with that in mind read the following from the React docs:

There should be a single “source of truth” for any data that changes in a React application. Usually, the state is first added to the component that needs it for rendering. Then, if other components also need it, you can lift it up to their closest common ancestor. Instead of trying to sync the state between different components, you should rely on the top-down data flow.

Lifting state involves writing more “boilerplate” code than two-way binding approaches, but as a benefit, it takes less work to find and isolate bugs. 
Enter fullscreen mode Exit fullscreen mode

So, the idea is to only have the parent have full control over the state, the child should receive the parent's state and control to that state as props. This way if there's a bug, you always know where to look for - the parent. You can grant control to the state via props by wrapping the setter in a function in the parent. Doing so will also allow you to control how the child mutates the parent's state too.

TLDR: Wrapping the setter in a function and passing it as a prop, then calling it in the child makes it look like the parent is changing the state, not the child.

Thread Thread
 
emma profile image
Emma Goto 🍙

Makes sense, thanks for the detailed explanation :)