venus
venus3y ago

Is it possible to avoid prop drilling in this scenario?

Hello, is it possible to reset the input text from top level component Main other way than just prop drilling input text state from Main component?
const Main = () => {
return (
<>
<button onClick={() => {}}>Reset Input</button>
<SearchInput onValueChange={(v) => {}} />
</>
);
};

export const SearchInput = ({ onValueChange }) => {
const [text, setText] = useState('');
const [value] = useDebounce(text, 300);

useEffect(() => onValueChange(value), [value]);

return (
<input type="text" value={text} onChange={(e) => setText(e.target.value)} />
);
};
const Main = () => {
return (
<>
<button onClick={() => {}}>Reset Input</button>
<SearchInput onValueChange={(v) => {}} />
</>
);
};

export const SearchInput = ({ onValueChange }) => {
const [text, setText] = useState('');
const [value] = useDebounce(text, 300);

useEffect(() => onValueChange(value), [value]);

return (
<input type="text" value={text} onChange={(e) => setText(e.target.value)} />
);
};
3 Replies
Unknown User
Unknown User3y ago
Message Not Public
Sign In & Join Server To View
reactibot
reactibot3y ago
Lifting State Up
Often, several components need to reflect the same changing data. We recommend lifting the shared state up to their closest common ancestor. Let’s see how this works in action. https://beta.reactjs.org/learn/sharing-state-between-components
Unknown User
Unknown User3y ago
Message Not Public
Sign In & Join Server To View