Passing signal as prop #749
-
|
Assuming I have a signal in a parent comp, and I want to pass the signal value to a child comp, what is the difference, in term of performance/behavior, between passing the signal value as props vs passing the signal getter function as props for example: passing signal getter as props function DisplayCount(props) {
return <div>Count: {props.count()} </div>
}
function Counter() {
const [count, setCount] = createSignal(0);
setInterval(() => setCount(count() + 1), 1000);
return <DisplayCount count={count} />;
}passing signal value function DisplayCount(props) {
return <div>Count: {props.count} </div>
}
function Counter() {
const [count, setCount] = createSignal(0);
setInterval(() => setCount(count() + 1), 1000);
return <DisplayCount count={count()} />;
} |
Beta Was this translation helpful? Give feedback.
Replies: 3 comments 7 replies
-
|
There's some difference but this might not be intuitive to some users:
Accessing their values (calling the signal prop vs accessing the reactive prop) should be the same however a "reactive prop" isn't always about signals. |
Beta Was this translation helpful? Give feedback.
-
|
From what I understand from you the following effect in the child comp should be triggered only once, because it doesn't have reactivity: function DisplayCount(props) {
createEffect(() => { console.log(props.count) });
return <div>Count: {props.count} </div>
}
function Counter() {
const [count, setCount] = createSignal(0);
setInterval(() => setCount(count() + 1), 1000);
return <DisplayCount count={count()} />;
}but it is called every time count updates. What am I missing? |
Beta Was this translation helpful? Give feedback.
-
|
Yeah the reason I designed it was to be uniform when people passed literal values. Generally passing the signal value is what we recommend because it mirrors passing any value. You consume it the same way inside your component. No checking for |
Beta Was this translation helpful? Give feedback.
There's some difference but this might not be intuitive to some users:
count={count}, the expression is treated as "static" therefore isn't wrapped into a getter and is never considered as reactive. With this in mind,props.countcan be safely destructured without losing reactivity (since it wasn't there, in the first place).count={count()}, the expression is treated as "reactive" and is therefore wrapped into a getter. This, however, cannot be destructured outside of reactive scopes (e.g. createEffect) without losing reactivity.Accessing their values (calling the signal prop vs accessing the reactive prop) should be the same however a "reactive prop" isn't always about sign…