Search...
Log in Create account
Rahul Sharma Rahul Sharma
Posted on Sep 21, 2022 • Updated on Dec 29, 2022
Follow
16 1
17
✔ I’m currently learning about Flutter ✔ Ask me anything
React.js state management using signals
you want, If I'm alive I will answer within seconds 😉 ✔ I
Always try to learn something new & then sleep till it stores in
4 the brain 😎
#react #signals #preact #javascript
LOCATION
Bangalore, India
23 JOINED
Mar 14, 2022
React.js (2 Part Series)
1 useAsync hook with cache More from Rahul Sharma
2 React.js state management using signals What, Why and How Javascript Static Initialization Blocks?
#javascript #webdev #beginners #programming
A signal is an object that has a value and can be observed for changes. It is similar to a state, but it is not
Create an HTTP server using 1 command
bound to a component. It can be used to share data between components. It updates the components when
#webdev #javascript #tutorial #programming
the signal changes and updates the UI without re-rendering the whole component.
Exploring the Power of new.target in JavaScript
#javascript #webdev #beginners #tutorial
DEV Community
🌚 Life is too short to browse
without dark mode
![Image description]
This lets us skip all of the expensive rendering work and jump immediately to any components in the tree that
access the signal's value property.
In this article, I'll be using signals with React.
Installation
npm i @preact/signals-react
Create a signal
We can create state(signal) using signal function, signal function takes default signal(value) as an parameter
and returns Proxy object. The value of the signal can be accessed using the signal.value property. We can also
set the value of the signal using signal.value = newValue .
import { signal } from "@preact/signals-react";
const count = signal(0);
Counter Component
import React from "react";
import { signal } from "@preact/signals-react";
const count = signal(0);
const Counter = () => <button onClick={() => count.value++}>{count}</button>;
NOTE: React Hooks can only be called inside the root of the component, Signal can be used outside of a component.
Effect
We don't have to pass dependencies array like the useEffect hook. It'll automatically detect dependencies and
call effect only when dependencies change.
import React from "react";
import { signal, effect } from "@preact/signals-react";
const count = signal(0);
const Counter = () => {
effect(() => console.log(count.value));
return <button onClick={() => count.value++}>{count}</button>;
};
Advanced Usage
When working with signals outside of the component tree, you may have noticed that computed signals don't
re-compute unless you actively read their value.
const count = signal(0);
const double = computed(() => count.value * 2);
const Counter = () => {
effect(() => console.log(count.value));
return (
<div>
<h1>{double}</h1>
<button onClick={() => count.value++}>{count}</button>
</div>
);
};
Live Demo: Counter Demo
Thank you for reading 😊
Got any questions or additional? please leave a comment.
Must Read If you haven't
useAsync hook with cache
Getting started with SolidJs – A Beginner's Guide
React best practices and patterns to reduce code
3 steps to create custom state management library with React and Context API
How to cancel Javascript API request with AbortController
13 Typescript Utility: A Cheat Sheet for Developer
More content at Dev.to.
Catch me on YouTube, Github, Twitter, LinkedIn, Medium, Stackblitz, Hashnode, HackerNoon, and Blogspot.
React.js (2 Part Series)
1 useAsync hook with cache
2 React.js state management using signals
Top comments (4) Subscribe
Add to the discussion
DuocNgo • Mar 2
hi Rahul, can you use object with signal. thanks in advance.
Reply
Rafael Melo • Mar 4
yes you can, check this section here on docs
Combining multiple updates into one
preactjs.com/guide/v10/signals#usa...
1 like Reply
DuocNgo • Mar 7 • Edited on Mar 7
import React from 'react'
import { signal } from '@preact/signals-react'
function Todos(props) {
const todos = signal([
{ name: '123'},
])
const addToDo = () => {
todos.value = [...todos.value, { name: '123123'}]
}
return (
<div>
<button onClick={() => {
addToDo();
}}>add to do</button>
{
todos.value.map(({ name }, index) => (<div key={index} style={{
fontWeight: 'bold'
}}>{name}</div>))
}
</div>
)
}
export default Todos
i have tried, but my UI didn't update after click add new Todo.
Reply
Rafael Melo • Mar 4
isnt this 1:1 with the preact docs?
preactjs.com/guide/v10/signals#usa...
1 like Reply
Code of Conduct • Report abuse
DEV Community
Visualizing Promises and Async/Await 🤯
☝ Check out this all-time classic DEV post
Read next
Building the largest Notifications Library in the world using ChatGPT, React, and NodeJS 🤯
Nevo David - Feb 13
Setting up authentication in Astro with Prisma and Planetscale
Thomas Ledoux - Feb 26
Building Serverless Applications with React
Kauna Hassan - Feb 25
My VS Code setup
Jatin Sharma - Feb 4
DEV Community — A constructive and inclusive social network for software developers. With you every step of your journey.
Home Listings Podcasts Videos Tags FAQ Forem Shop Sponsors About Contact Guides Software comparisons
Code of Conduct Privacy Policy Terms of use
Built on Forem — the open source software that powers DEV and other inclusive communities.
Made with love and Ruby on Rails. DEV Community © 2016 - 2023.