3 React concepts I wish I knew when I started
Published: 2021-06-21 14:51:01

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.

###### This is for beginners and people who are the same kind.
```
function App() {
  console.log("app")
  const [state, toggle] = useState(true);
  return (
    <div>
    <h2>{`${state}`}</h2>
    <button onClick={() => { toggle(!state) }}>Toggle</button>
    </div>
 )
}

```

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.
I expected a single log on each button click. But I noticed every time the button was clicked, there were two logs.



![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/yqs208f505zcyn0uugsy.gif)

I moved on without being bothered by this behaviour.
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 <React.StrictMode></React.StrictMode>.
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.”

If you’re using create-react-app , you may notice that your app is wrapped in <React.StrictMode></React.StrictMode> in index.js.
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 [here](https://reactjs.org/docs/strict-mode.html).


**2. Keys**
When rendering multiple components, we usually map over lists like,

```
const numbers = [1, 2, 3, 4, 5];
const listItems = numbers.map((number) =>
  <li key={number.toString()}>    {number}
  </li>
);
ReactDOM.render(
  <ul>{listItems}</ul>,  document.getElementById('root')
);

```

React uses keys to optimise performance. Read more about why keys are necessary, [here](https://reactjs.org/docs/reconciliation.html#component-elements-of-the-same-type) .
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.”
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.
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 [here](https://medium.com/@robinpokorny/index-as-a-key-is-an-anti-pattern-e0349aece318) . The article demonstrates the problem using a very good example of text inputs.

**3. Stale state**

The problem is, in some cases you don’t have the latest state at your disposal.
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.
Consider this piece of code,

```
function App() {
  
    const [state, toggle] = useState(0);
  
    useEffect(()=>{
    
    setInterval(()=>{
      console.log(`state ${state}`);
    },3000)
  
},[])
    return (
       <div>
       <h2>{`${state}`}</h2>
       <button onClick={() => { toggle(state+1) }}>Increase</button>
       </div>
)
}
```

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.

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/vp4ffffwy2tewlq4wyj5.gif)


The answer to ‘why’ , lies not in React but JavaScript itself. It is related to something known as closures. Read about closures [here](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Closures) .
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 [this](https://stackoverflow.com/questions/55154186/react-hooks-usestateuseeffectevent-gives-stale-state/55156813#55156813) SO answer which shows the proper way to use event listeners in useEffect.
It’s important to know that having fundamental JS knowledge should be given higher priority than having framework or library specific
 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.
Never underestimate the knowledge you’re gonna get just by looking at documentations, especially when they’re as good as React’s.
**Thank you for reading Please Buy Me a Coffee https://www.buymeacoffee.com/rubengabriel !**