umma.dev

Using Signals in React Apps

What are Signals?

Another state management library!

How Are Signals Different from React Hooks?

You can render your data from a component lower in the DOM tree and re-use the signal practically anywhere without prop drilling! This means only rendering the data you need in a specific place rather than having to go up higher in the DOM, where this data loading can be costly to the rest of your application.

However it is common in most applications to have a central store of your data fetching and state management, and Signals is no different. This is particuarly important for when it comes to testing ad it is advised to do this rather than having signals in components. The advantage to doing this however unlike hooks is, the signal doesn’t have to be imported into a parent component.

Although context does something similar, the data is rendered higher up in the DOM tree, whereas with Signal as stated previously the data is only rendered in the component it’s used in.

Unlike useEffect, there doesn’t seem to be any side effects of using it.

Example of Using Signals

Why Does Where Data Render Matter in React Apps?

Signals only update the components/part of the tree where they are used. In a traditional React application which uses hooks, these hooks typically sit on the parent level and get called each time a change is made to the child component; be this rendering an update from the API, making a post request etc.

Decreasing the amount of re-renders in a React application is important. One of the principles of React is reusability with components, hence the use of props, so it would only make sense you would also want to ensure efficient data loading within your app as well as efficiency with the UI that is rendered.

Let’s take for example you have two components which render the same UI, one is for adding and the other is for editing. It would not make sense to have a boolean to render one or the other because once you have rendered the component for example for the add component, it is not a case of un-rendering it on the page and this is also costly. It is more efficient to be able to tell your UI which functionality it is taking out, either add or edit.

For more information and more comprehensive guide, check out this post.