DEV Community

Inam_95
Inam_95

Posted on

React: Passing props from Child to Parent (alternative method for callbacks).

Props in React are used to pass data between components. This could be from parent to child or from child to parent. In this article, we will look at passing props from child to parent.

The usual or well-known method is pass a callback function as a prop from the parent to the child and update the state in parent component by calling the callback function in the child component.

Instead of that method let's use a hook to pass props from child to parent. To demonstrate this let's say we have a input and when user update the input we call and endpoint with the user entered input value.

// Parent Component
const Main = () => {
  const { inputValue, render } = useInput();

  // Make the api call using the inputValue

  return (
    <div>
      <p>{inputValue}</p>
      {render}
    </div>
  );
};

// useInput Hook
const useInput = () => {
  const [inputValue, setInputValue] = useState('');
  return {
    inputValue,
    render: (
      <div>
        <input
          value={inputValue}
          onChange={e => setInputValue(e.target.value)}
        />
      </div>
    )
  };
};
Enter fullscreen mode Exit fullscreen mode

Here the useInput hook handles the inputValue state and also it handles the rendering (UI) part of the input as well. In the parent component I have destruct the inputValue and render form the useInput hook and use those values to render the UI and make the api call with inputValue.

Instead of keeping the inputValue state in the parent component and pass the inputValue and setInputValue as props to a child component which renders the input, Here I have extract those logics to a hook which I believe makes the code more clean and readable.

Conclusion
This is just a simple example to demonstrate this method. Imagine if I had a whole filter component with few more inputs, checkboxes, dropdown selectors then this method would really make sense.

Try this out and let me know your thoughts...😋

Top comments (1)

Collapse
 
brense profile image
Rense Bakker

Returning render functions like that may seem clever, but it's not very good for performance and debugging, especially if the render function is not memoized with useCallback.