How to store value of variable if it is changed inside of ajax callback function?
The ajax callback is not for form logic. It's only supposed to send back a new version of $form or part of it in a wrapper. Or in more advanced cases a collection of ajax commands.

Use instead buildForm(). You can check which button was clicked with $form_state-&gt;getTriggeringElement().      

  public function buildForm(array $form, FormStateInterface $form_state) {

    $form['#prefix'] = '&lt;div id="ajax_wrapper"&gt;';
    $form['#suffix'] = '&lt;/div&gt;';

    $i = $form_state-&gt;get('elem') ? $form_state-&gt;get('elem') : 1;
    $trigger = $form_state-&gt;getTriggeringElement();
    if (isset($trigger['#ajax']['callback']) &amp;&amp; $trigger['#ajax']['callback'] === '::addMore') {
      $i++;
    }
    $form_state-&gt;set('elem', $i);

    $form['counter'] = [
      '#markup' =&gt; $form_state-&gt;get('elem') ?? 1,
    ];

    $form['btn'] = [
      '#type' =&gt; 'button',
      '#value' =&gt; 'Btn',
      '#ajax' =&gt; [
        'callback' =&gt; '::addMore',
        'wrapper' =&gt; 'ajax_wrapper',
      ]
    ];

    return $form;
  }

  public function addMore(array &amp;$form, FormStateInterface $form_state){
    return $form;
  }

  public function submitForm(array &amp;$form, FormStateInterface $form_state){

  }