<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>Forem: Ruben Gabrielyan</title>
    <description>The latest articles on Forem by Ruben Gabrielyan (@rubengabrielian).</description>
    <link>https://forem.com/rubengabrielian</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F653247%2F2b45968c-401d-49f2-83bc-ca269af5f78f.jpeg</url>
      <title>Forem: Ruben Gabrielyan</title>
      <link>https://forem.com/rubengabrielian</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://forem.com/feed/rubengabrielian"/>
    <language>en</language>
    <item>
      <title>Stop Writing JavaScript Like This
</title>
      <dc:creator>Ruben Gabrielyan</dc:creator>
      <pubDate>Thu, 14 Oct 2021 14:53:16 +0000</pubDate>
      <link>https://forem.com/rubengabrielian/stop-writing-javascript-like-this-8po</link>
      <guid>https://forem.com/rubengabrielian/stop-writing-javascript-like-this-8po</guid>
      <description>&lt;p&gt;Most of us are used to writing JavaScript code for a long time. But we might not have updated ourselves with new features which can solve your issues with minimal code. These techniques can help you write clean and optimized JavaScript Code. Today, I’ll be summarizing some optimized JavaScript code snippets which can help you develop your skills.&lt;/p&gt;

&lt;h3&gt;
  
  
  1. Shorthand for if with multiple || conditions
&lt;/h3&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;if (fruit === 'apple' || fruit === 'orange' || fruit === 'banana' || fruit ==='grapes') {
    //code
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Instead of using multiple || (OR) conditions, we can use an array with the values and use the includes() method.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;if (['apple', 'orange', 'banana', 'grapes'].includes(fruit)) {
   //code
}

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  2. Shorthand for if with multiple &amp;amp;&amp;amp; conditions
&lt;/h3&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;if(obj &amp;amp;&amp;amp; obj.address &amp;amp;&amp;amp; obj.address.postalCode) {
    console.log(obj.address.postalCode)
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Use optional chaining (?.) to replace this snippet.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;console.log(obj?.address?.postalCode);
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  3. Shorthand for null, undefined, and empty if checks
&lt;/h3&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;if (first !== null || first !== undefined || first !== '') {
    let second = first;
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Instead of writing so many checks, we can write it better this way using ||&lt;br&gt;
(OR) operator.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const second = first || '';
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  4. Shorthand for switch case
&lt;/h3&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;switch (number) {
  case 1:
     return 'one';
  case 2:
     return 'two';
  default:
     return;
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Use a map/ object to write it in a cleaner way.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const data = {
  1: 'one',
  2: 'two'
};
//Access it using
data[num]
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  5. Shorthand for functions with a single line
&lt;/h3&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;function doubleOf(value) {
  return 2 * value;
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Use the arrow function to shorten it.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const doubleOf = (value) =&amp;gt; 2 * value
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h1&gt;
  
  
  &lt;a href="https://www.buymeacoffee.com/rubengabriel"&gt;Buy me a coffee&lt;/a&gt;
&lt;/h1&gt;

</description>
      <category>javascript</category>
      <category>webdev</category>
      <category>programming</category>
    </item>
    <item>
      <title>How To Setup Redux with Redux Toolkit
</title>
      <dc:creator>Ruben Gabrielyan</dc:creator>
      <pubDate>Tue, 22 Jun 2021 13:13:21 +0000</pubDate>
      <link>https://forem.com/rubengabrielian/how-to-setup-redux-with-redux-toolkit-5fgh</link>
      <guid>https://forem.com/rubengabrielian/how-to-setup-redux-with-redux-toolkit-5fgh</guid>
      <description>&lt;p&gt;Developing modern web applications involves not only UI building but also state management. One of the most widespread libraries for this is Redux. In this tutorial you will learn how to setup Redux using latest libraries and techniques available in 2020 and Redux Toolkit which will simplify your logic and ensure that your setup has good defaults.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Why to choose Redux Toolkit&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Redux is a good fundament for the opening but to simplify working it is recommended to use the Redux Toolkit. It was created to help address three common concerns about Redux:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;"Configuring a Redux store is too complicated"&lt;/li&gt;
&lt;li&gt;"I have to add a lot of packages to get Redux to do anything useful"&lt;/li&gt;
&lt;li&gt;"Redux requires too much boilerplate code"&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;It has functions that build according to &lt;a href="https://redux.js.org/style-guide/style-guide"&gt;Redux best practices&lt;/a&gt; . It includes several utility functions that simplify the most common Redux use cases, including store setup, defining reducers, immutable update logic with Immer, and even allows creating entire "slices" of state at once without need to write action creators.&lt;/p&gt;

&lt;p&gt;It comes as preconfigured bundle of the most widely used Redux addons, like Redux Thunk for async logic and Reselect for writing selector functions, so that you can use them right away. It also allows your to overwrite all of its settings, for example its very easy to use redux-saga or any other middleware with it.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;How to setup Create-React-App With Redux&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;For this redux tutorial lets start with setup new react application with CRA:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;npm install -g create-react-app
create-react-app redux-tutorial
cd redux-tutorial

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Next we will add redux with:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;npm install --save react-redux @reduxjs/toolkit

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Firstly configure store. Create file src/store/index.js containing:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import { configureStore } from '@reduxjs/toolkit'
import { combineReducers } from 'redux'
const reducer = combineReducers({
  // here we will be adding reducers
})
const store = configureStore({
  reducer,
})
export default store;

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;configureStore accepts a single object rather that multiple function arguments. It's because under the hood, the store has been configured to allow using the Redux DevTools Extension and has had some Redux middleware included by default.&lt;/p&gt;

&lt;p&gt;Then we need to connect our store to the React application. Import it into index.js like this:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;...
import { Provider } from 'react-redux'
import store from './store'
ReactDOM.render(
  &amp;lt;Provider store={store}&amp;gt;
    &amp;lt;App /&amp;gt;
  &amp;lt;/Provider&amp;gt;,
  document.getElementById('root')
)

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Provider wraps the App and the whole application has access to Redux. If you start your application with npm start and open Redux Dev Tools you should see @@INIT. Congratulations you have setup redux!&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;How To Structure Your Redux&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Lets now setup Redux authentication and implement simple login form and logout button shown after authentication. Redux itself does not care about how your application's folders and files are structured. However, co-locating logic for a given feature in one place typically makes it easier to maintain that code. Redux.org recommend that most applications should structure files using a "feature folder" approach (all files for a feature in the same folder) or the "ducks" pattern (all Redux logic for a feature in a single file), rather than splitting logic across separate folders by "type" of code (reducers, actions, etc).&lt;/p&gt;

&lt;p&gt;Lets add src/store/user.js store slice:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import { createSlice } from '@reduxjs/toolkit'
// Slice
const slice = createSlice({
  name: 'user',
  initialState: {
    user: null,
  },
  reducers: {
    loginSuccess: (state, action) =&amp;gt; {
      state.user = action.payload;
    },
    logoutSuccess: (state, action) =&amp;gt;  {
      state.user = null;
    },
  },
});
export default slice.reducer
// Actions
const { loginSuccess, logoutSuccess } = slice.actions
export const login = ({ username, password }) =&amp;gt; async dispatch =&amp;gt; {
  try {
    // const res = await api.post('/api/auth/login/', { username, password })
    dispatch(loginSuccess({username}));
  } catch (e) {
    return console.error(e.message);
  }
}
export const logout = () =&amp;gt; async dispatch =&amp;gt; {
  try {
    // const res = await api.post('/api/auth/logout/')
    return dispatch(logoutSuccess())
  } catch (e) {
    return console.error(e.message);
  }
}

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The store feature file contains createSlice that returns a "slice" object that contains the generated reducer function as a field named reducer, and the generated action creators inside an object called actions.&lt;/p&gt;

&lt;p&gt;At the bottom we can import the action creators and export them directly or use them within async actions, like login and logout.&lt;/p&gt;

&lt;p&gt;To connect reducer into Redux, we have add add it to the main reducer in store/index.js:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;...
import user from './user'
const reducer = combineReducers({
  user,
})

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Connecting Redux to Components with useDispatch and useSelector&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Our redux setup is ready. Now lets configurate Authentication form. For this we will use Formik. Type the following into your terminal:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;npm install --save formik

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Now we can create following src/App.js component:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;...
import {useDispatch, useSelector} from 'react-redux'
import {Field, Form, Formik} from 'formik'
import {login, logout} from './store/user'
function App() {
  const dispatch = useDispatch()
  const { user } = useSelector(state =&amp;gt; state.user)
  if (user) {
    return (
      &amp;lt;div&amp;gt;
        Hi, {user.username}!
        &amp;lt;button onClick={() =&amp;gt; dispatch(logout())}&amp;gt;Logout&amp;lt;/button&amp;gt;
      &amp;lt;/div&amp;gt;
    )
  }
  return (
    &amp;lt;div&amp;gt;
      &amp;lt;Formik
        initialValues={{ username: '', password: '' }}
        onSubmit={(values) =&amp;gt; { dispatch(login(values)) }}
      &amp;gt;
        {({ isSubmitting }) =&amp;gt; (
          &amp;lt;Form&amp;gt;
            &amp;lt;Field type="text" name="username" /&amp;gt;
            &amp;lt;Field type="password" name="password" /&amp;gt;
            &amp;lt;button type="submit" disabled={isSubmitting}&amp;gt;Login&amp;lt;/button&amp;gt;
          &amp;lt;/Form&amp;gt;
        )}
      &amp;lt;/Formik&amp;gt;
    &amp;lt;/div&amp;gt;
  );
}

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Please note that there is no connect! With useDispatch and useSelector we can now integrate Redux with pure components using hooks! We just need to wrap App with Provider and there is much less boilerplate compared to connect.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;How Keep User Authenticated on Page Reload&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Probably you've noticed that authentication is reseted on every page reload.&lt;/p&gt;

&lt;p&gt;That is very easy to fix with localStorage with just a few lines added to src/store/user.js&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;+const initialUser = localStorage.getItem('user')
+  ? JSON.parse(localStorage.getItem('user'))
+  : null
+
const slice = createSlice({
  name: 'user',
  initialState: {
-    user: null,
+    user: initialUser,
  },
  reducers: {
    loginSuccess: (state, action) =&amp;gt; {
      state.user = action.payload;
+      localStorage.setItem('user', JSON.stringify(action.payload))
    },
    logoutSuccess: (state, action) =&amp;gt;  {
      state.user = null;
+      localStorage.removeItem('user')
    },
  },
});

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;How to Store Token&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;My favorite API client library is Axios. I prefer Axios over built-in APIs for its ease of use and extra features like xsrf token support and interceptors.&lt;/p&gt;

&lt;p&gt;Here is sample configuration that I often use:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const api = axios.create({
  baseURL: '/',
  headers: {
    'Content-Type': 'application/json'
  },
})
api.interceptors.request.use(
  config =&amp;gt; {
    const token = localStorage.getItem('token')
    if (token) {
      config.headers['Authorization'] = `Token ${token}`
    }
    return config
  },
  error =&amp;gt; Promise.reject(error)
)
export default api

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;How to Redirect after login&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;The easiest way to redirect user after redux action is to use Redirect component provided by React.&lt;/p&gt;

&lt;p&gt;This can be one within Login form component, for example with code like this:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;if (user) {
    return (
      &amp;lt;Redirect to={'/home'} /&amp;gt;
    )
  }

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



</description>
      <category>javascript</category>
      <category>react</category>
      <category>redux</category>
    </item>
    <item>
      <title>3 React concepts I wish I knew when I started</title>
      <dc:creator>Ruben Gabrielyan</dc:creator>
      <pubDate>Mon, 21 Jun 2021 14:51:01 +0000</pubDate>
      <link>https://forem.com/rubengabrielian/3-react-concepts-i-wish-i-knew-when-i-started-4bim</link>
      <guid>https://forem.com/rubengabrielian/3-react-concepts-i-wish-i-knew-when-i-started-4bim</guid>
      <description>&lt;p&gt;When I stumbled upon React, I barely had any JS knowledge. I had been told by my peers and the internet, of course, that some JavaScript knowledge would be necessary to start with React JS, but, I took the chance. Belonging to the kind of people that “learn by doing” , I went on to explore the JavaScript world and JSX that comes with React.&lt;/p&gt;

&lt;h6&gt;
  
  
  This is for beginners and people who are the same kind.
&lt;/h6&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;function App() {
  console.log("app")
  const [state, toggle] = useState(true);
  return (
    &amp;lt;div&amp;gt;
    &amp;lt;h2&amp;gt;{`${state}`}&amp;lt;/h2&amp;gt;
    &amp;lt;button onClick={() =&amp;gt; { toggle(!state) }}&amp;gt;Toggle&amp;lt;/button&amp;gt;
    &amp;lt;/div&amp;gt;
 )
}

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;I had a heading and a button to toggle it’s content. I also had a console.log inside the function to log a message every time state was changed and a re render was triggered.&lt;br&gt;
I expected a single log on each button click. But I noticed every time the button was clicked, there were two logs.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fyqs208f505zcyn0uugsy.gif" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fyqs208f505zcyn0uugsy.gif" alt="Alt Text"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;I moved on without being bothered by this behaviour.&lt;br&gt;
Later, when I noticed the same behaviour in something more complex , it bugged me. That’s when I realised that this behaviour was only visible in development and not in production. I searched online and found that, it was due to Strict Mode. I noticed that in index.js, my app was wrapped within .&lt;br&gt;
Quoting from the ReactJS documentation itself:  “Strict mode can’t automatically detect side effects for you, but it can help you spot them by making them a little more deterministic. This is done by intentionally double-invoking the following functions: Class component constructor, render, and shouldComponentUpdate methods.”&lt;/p&gt;

&lt;p&gt;If you’re using create-react-app , you may notice that your app is wrapped in  in index.js.&lt;br&gt;
So, this was the issue. This is why I had two logs on every render. I wish I had known this. To read more about Strict Mode check &lt;a href="https://reactjs.org/docs/strict-mode.html" rel="noopener noreferrer"&gt;here&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;2. Keys&lt;/strong&gt;&lt;br&gt;
When rendering multiple components, we usually map over lists like,&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const numbers = [1, 2, 3, 4, 5];
const listItems = numbers.map((number) =&amp;gt;
  &amp;lt;li key={number.toString()}&amp;gt;    {number}
  &amp;lt;/li&amp;gt;
);
ReactDOM.render(
  &amp;lt;ul&amp;gt;{listItems}&amp;lt;/ul&amp;gt;,  document.getElementById('root')
);

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;React uses keys to optimise performance. Read more about why keys are necessary, &lt;a href="https://reactjs.org/docs/reconciliation.html#component-elements-of-the-same-type" rel="noopener noreferrer"&gt;here&lt;/a&gt; .&lt;br&gt;
From the official docs: “Keys help React identify which items have changed, are added, or are removed. Keys should be given to the elements inside the array to give the elements a stable identity.”&lt;br&gt;
Now one obvious idea that would come to mind: we could use the array index as the key. But wait, think again, because it is not the recommended approach.&lt;br&gt;
Think about what would happen if the list is prepended, since React only relies on the keys to decide if the DOM should be updated. Read about this &lt;a href="https://medium.com/@robinpokorny/index-as-a-key-is-an-anti-pattern-e0349aece318" rel="noopener noreferrer"&gt;here&lt;/a&gt; . The article demonstrates the problem using a very good example of text inputs.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;3. Stale state&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;The problem is, in some cases you don’t have the latest state at your disposal.&lt;br&gt;
This one, I had to struggle a lot to get my head around. For someone who had no idea about closures and why they were important in the context of React, I had to read a lot about the “behind-the-scenes” of React.&lt;br&gt;
Consider this piece of code,&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;function App() {

    const [state, toggle] = useState(0);

    useEffect(()=&amp;gt;{

    setInterval(()=&amp;gt;{
      console.log(`state ${state}`);
    },3000)

},[])
    return (
       &amp;lt;div&amp;gt;
       &amp;lt;h2&amp;gt;{`${state}`}&amp;lt;/h2&amp;gt;
       &amp;lt;button onClick={() =&amp;gt; { toggle(state+1) }}&amp;gt;Increase&amp;lt;/button&amp;gt;
       &amp;lt;/div&amp;gt;
)
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;On clicking the button and updating the state, there is no change in the logs. The logs show the initial state which is 0. Look at the GIF below.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fvp4ffffwy2tewlq4wyj5.gif" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fvp4ffffwy2tewlq4wyj5.gif" alt="Alt Text"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;The answer to ‘why’ , lies not in React but JavaScript itself. It is related to something known as closures. Read about closures &lt;a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Closures" rel="noopener noreferrer"&gt;here&lt;/a&gt; .&lt;br&gt;
This is not a huge problem here, but imagine an event listener being attached to an object, in useEffect and getting stale state inside it. Check out &lt;a href="https://stackoverflow.com/questions/55154186/react-hooks-usestateuseeffectevent-gives-stale-state/55156813#55156813" rel="noopener noreferrer"&gt;this&lt;/a&gt; SO answer which shows the proper way to use event listeners in useEffect.&lt;br&gt;
It’s important to know that having fundamental JS knowledge should be given higher priority than having framework or library specific&lt;br&gt;
 knowledge. Because, regardless of what library you use , you still have to write JS code and deal with JS related concerns. It’s important not to limit yourself to a specific framework/library and it’s possible only by having a strong JS base.&lt;br&gt;
Never underestimate the knowledge you’re gonna get just by looking at documentations, especially when they’re as good as React’s.&lt;br&gt;
&lt;strong&gt;Thank you for reading Please Buy Me a Coffee &lt;a href="https://www.buymeacoffee.com/rubengabriel" rel="noopener noreferrer"&gt;https://www.buymeacoffee.com/rubengabriel&lt;/a&gt; !&lt;/strong&gt;&lt;/p&gt;

</description>
    </item>
  </channel>
</rss>
