title: How to listen the state changes in svelte like useEffect
body: <p>I have read some article about state change listener, As I am a very beginner to the svelte environment I can't figure out what is the most efficient way to listen to the state change.</p>
  <p>Let us take  state variable  as <code>X</code> and <code>Y</code></p>
  <h3>Method 1:</h3>
  <pre class="lang-js prettyprint-override"><code>$: if (X||Y) {
      console.log(&quot;yes&quot;);
  }
  </code></pre>
  <h3>Method 2:</h3>
  <p>Use a combination of <code>afterUpdate</code> and <code>onDestroy</code></p>
  <p>REPL: <a href="https://svelte.dev/repl/300c16ee38af49e98261eef02a9b04a8?version=3.38.2" rel="nofollow noreferrer">https://svelte.dev/repl/300c16ee38af49e98261eef02a9b04a8?version=3.38.2</a></p>
  <pre class="lang-js prettyprint-override"><code>import { afterUpdate, onDestroy } from 'svelte';
  
  export function useEffect(cb, deps) {
      let cleanup;
      
      function apply() {
          if (cleanup) cleanup();
          cleanup = cb();
      }
      
      if (deps) {
          let values = [];
          afterUpdate(() =&gt; {
              const new_values = deps();
              if (new_values.some((value, i) =&gt; value !== values[i])) {
                  apply();
                  values = new_values;
              }
          });
      } else {
          // no deps = always run
          afterUpdate(apply);
      }
      
      onDestroy(() =&gt; {
          if (cleanup) cleanup();
      });
  }
  </code></pre>
  <h3>Method 3:</h3>
  <p>Use <code>writable</code> and <code>subscribe</code></p>
  <pre class="lang-html prettyprint-override"><code>
  &lt;script&gt;
  import { writable } from 'svelte/store';
  const X = writable(0);
  const Y = writable(0);
  
  
  X.subscribe(value =&gt; {
      console.log(&quot;X was changed&quot;, value);
  });
  
  
  Y.subscribe(value =&gt; {
        console.log(&quot;Y was changed&quot;, value);
  });
  
  &lt;/script&gt;
  
  &lt;button on:click={(e)=&gt;{
      X.update((val)=&gt;val++)
  }}&gt;Change X&lt;/button&gt;
  &lt;button on:click={(e)=&gt;{
      Y.update((val)=&gt;val++)
  }}&gt;Change Y&lt;/button&gt;
  </code></pre>