🤓 Signal( ) are most underrated in React.js

-signal(-)-are-most-underrated-in-react.js

Welcome

Hey guys! Today I want to talk about something that is super cool in react but not many people talk about – useSignal()!

When I first learned react I was really into using hooks like useState() and useEffect() because they make it so easy to add reactivity and side effects to components. But one of my friend told me about another way to do it called signals that is built into react and I think its awesome!

useSignal() lets you create signals that components can subscribe and unsubscribe from. This is really useful when you want to centralize your state management or communicate between components without prop drilling.

For example👉 : let’s say we have a Parent component and Child component and when the parent’s state changes we want the child to update. With hooks we might do:

// Parent
function Parent() {
  const [count, setCount] = useState(0);

  return (
    <div>
      <button onClick={() => setCount(count + 1)}>Incrementbutton> 
      <Child count={count} />
    div>
  )
}

// Child 
function Child({ count }) {
  return <div>Count: {count}div>
}

This works but we are prop drilling the count down. With signals we can do:

// Create signal
const countSignal = useSignal(0); 

function Parent() {

  return (
    <div>
      <button onClick={() => countSignal.setValue(countSignal.value + 1)}>
        Increment  
      button>

      <Child />
    div>
  )
}

function Child() {

  countSignal.subscribe(count => {
    // This will update when parent changes value
  })

  return <div>Count: {countSignal.value}div>
}

Much cleaner ✨ right?! No more prop drilling.

Signals are also really useful** when you want to consolidate your state management**. You could create signals for things like auth status, loading states, etc and have any component subscribe to them. This prevents spreading state everywhere.

So in summary 📃,

while react hooks are awesome, but don’t forget about signals!

They are really useful for centralized state management between components 😁 Give them a try on your next project!

Meet you in next Blog 🚀

Follow me in Github✅

Happy Coding 👋

Total
0
Shares
Leave a Reply

Your email address will not be published. Required fields are marked *

Previous Post
how-to-incorporate-ai-chat-and-software-into-your-seo-workflow

How to Incorporate AI Chat and Software into Your SEO Workflow

Next Post
doing-23-micro-launches-instead-of-just-1-platform

Doing 23 micro launches instead of just 1 platform

Related Posts