5 Ways to pass data between components using React API

Ilan Roitlender
Webtips
Published in
4 min readJun 2, 2020

React is a powerful library that makes your development experience fun and fast so you can focus on building modern, interactive web applications but with a great ( and powerful ) API comes great responsibility.

Thinking in React

The first thing that comes in mind when building new screen in react application is to break the UI into component hierarchy with small components. It will help you share, organize and reuse components between apps and projects.

We talked about breaking down the components but what about sharing data and methods between components?

But what if another component need the same logic for mouse event?

Here we can see a component that simply render to the screen paragraph that shows the current mouse position.

The problem

We are reusing our components piece by piece but what about props and data?

Lucky for us React API comes to the rescue and give us a various options to help us reduce the amount of duplicate code, keep our code as much reusable as possible and shrink your lines of code.

  1. React.cloneElement to the rescue:
    This is a Top-Level-API, that receives a react element and makes a shallow copy of the element and returns a new element that contains the original element’s props as well the new props attached to it.
    React.cloneElement() is almost equivalent to:
    <element.type {...element.props} {...props}>{children}</element.type>

Use React.Children.map method to create new array of elements (children) and attach additional props to each component.

Why should we use this approach?
-
Well, the simple response is we should not. React evolved so much in the past few year so I cant see any good reason to use it when React is giving you many and better options to play and experiment with, but still its good to know about this API in case you will need it.

2. renderProps — Passing values using functions
Every React developer come across with this method, for example if you ever used libraries like React Router, Formik or React-virtualized.

Note, If you are using static type checking library, its important to explicitly the children type, Since this technique is a little unusual- the children that passed to the component should be of type Function.

note: I`m using React.useCallback to memorize the function.

3. Using Higher-Order-Components to render props:
HOC is an advanced technique in React that helping us as developers to reuse components logic, as before you may come across in a third-party React libraries, such as Redux’s connect method.
A HOC function takes a component as an argument and returns a component. It transforms a component into another component and adds additional data or functionality.

mouseHOC receive App component and returns it with new prop mousePos.

4. Using Custom hooks useMousePos :
As I said before React is evolving all the time and without any doubt one of my favorite new additions is the use of new React Hooks API since React 16.8 .
Until now renderProps and HOC was the most common ways to share logic between components and the down side was that you required to add more components to your components tree.

This is a simple implementation of creating custom hook in our scenario comes in handy:

A custom Hook is a JavaScript function whose name starts with ”use” and that may call other Hooks.

useMouseHook receive reference to node container and attached an EventListener so it can update state and return the current mouse position.

Note, do not forget to add cleanup function to prevent memory leeks.

5. Using Context API :
React Context can be a great state management solution for React applications. It helps you to contain and handle application global state for small and large scale apps. By using Context you are passing down the components tree any prop or data without prop drilling.

context does NOT have to be global to the whole app, but can be applied to one part of your tree and you can (and probably should) have multiple and separated contexts in your app.

Note, this is a simple case and you are probably not going to use it to pass props like mouse position, in this example that I’m intentionally over-engineering to show how we can achieve the same goal like in other examples.

By wrapping component with contextPropvider, any nested child down the tree can access the Context state using usePosContext() .

Sandbox playground:

Conclusion

When starting building new features to our existing apps or planning UI Design, its important to start separate it into smaller sub components. Same goes about our data modal, methods and little pieces of data that are going to be shared between components.

React is a simple JavaScript library for building user interfaces, the API is very flexible and giving you a set of tools for quicker, easier and straightforward development.

To summarize with a personal note, In my opinion creating a custom hooks can solve many of the same problems with much cleaner syntax and without forcing you to add more components to the tree.

Happy coding!

--

--