DEV Community

Cover image for 3 React concepts I wish I knew when I started
Ruben Gabrielyan
Ruben Gabrielyan

Posted on • Edited on

3 React concepts I wish I knew when I started

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>
 )
}

Enter fullscreen mode Exit fullscreen mode

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

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 .
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 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.

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')
);

Enter fullscreen mode Exit fullscreen mode

React uses keys to optimise performance. Read more about why keys are necessary, here .
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 . 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>
)
}
Enter fullscreen mode Exit fullscreen mode

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

The answer to ‘why’ , lies not in React but JavaScript itself. It is related to something known as closures. Read about closures here .
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 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 !

Top comments (2)

Collapse
 
raibtoffoletto profile image
Raí B. Toffoletto • Edited

I usually use a literal with an unique prop and the index on keys to be sure that the key is unique (e.g. "${index}//${property}"), maybe it's a bit too much xD but works well for me.

Collapse
 
alexandrricov profile image
Alex

It depends: it will not work well in case you change order, remove items or add items in other positions then at the end of the list.