Building reusable components using React

Last updated 143 days ago by Nirmalya Ghosh

react

React is one of the most popular JavaScript libraries for building user interfaces. To build an application using React, you just need to build encapsulated components that can contain their own state. Your application should basically be a collection of composable React components which can be reused multiple times.

What are reusable components?

Reusable components are those React components that can be used multiple times in your application. As a result, they need to be generic enough so that it’s free from complex business logic. If a component contains any complex logic inside it, not only does it become difficult to reuse, it also becomes less maintainable. React Hooks are the perfect fit for reusable component logic.

undefined

For example, the App component below has a button which can’t be reused since it has the onClick prop hardcoded in it:

```hljs function handleClick(e) { // Some function which does fake API call fakeApiCall(e.target.value); }

function App() { return (

); } ```

The above code renders the following user interface:

undefined

Here, there is no way in which we can modify the text Submit which is rendered on the button.

Making a React component reusable

If we want to make the above component reusable, we need to make it more generic. First, we can make a separate Button function which can be imported and reused multiple times in our application:

```hljs function handleClick(e) { // Some function which does fake API call fakeApiCall(e.target.value); }

function Button() { return (

Read full Article