DEV Community

shaaandi
shaaandi

Posted on

Returning JSX from hooks

I want to know if there is any performance issue if I do this:

const useCounter = () => {
  const [counter, setCounter] = useState(0)

  const increment = () => setCounter(p => p + 1)

  return {
  jsx: {
    count: <div>{counter}</div>,
    incrementBtn: <button onClick={increment}>Add</button>
  },
  }
}
// parent:
const Parent = () => {
  const { jsx: { count, incrementBtn } } = useCounter()
  return (
    <div>
      {count}
      {incrementBtn}
    </div>
  )
}
Enter fullscreen mode Exit fullscreen mode

WHY I am doing this ?
The above is a very simple, meaningless, example I have created to just show what I want to do. However, I will list the motivation here.

Separation of concerns. I want to keep my app in three layers.

UI Layer- Any code the defines the core design -- for example, buttons, or maybe big components like a Map, Table.

Integration Layer- Any code the connects my UI with the API layer. Here we can think of using useQuery hooks to fetch data and then transform it into the UI layer.

Layout Layer - Any code the handles the final logic of keeping the above code in specified places in a view.

So, doing above, I came across cases where two components are tightly coupled and need to share state but I do want to give the final positioning power to the Layout layer, so in the case, I define those components in a hook with all the logic needed and then return them as JSX and then the layout layer places them where it wants.

Abstracting the inner state to components.

The second reason is to make the things more faster to develop for specific cases. For example, a component that provides a ui and also the state that changes upon interaction with that UI.

In summary, just want to know if there is any perf concern here in the above code. And if yes, please state how ? Thanks. ❤️

Top comments (3)

Collapse
 
albencfc profile image
Albenis Kërqeli

I think that putting jsx in usestate is bad practice or anti-pattern and this method should be avoided

Collapse
 
shaaandi profile image
shaaandi

I haven't added the jsx in useState ? Where you get that?

Collapse
 
albencfc profile image
Albenis Kërqeli

You didn't add jsx in usestate hook but you are returning jsx from custom hook , that is bad practice