Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
June 21, 2021 02:51 pm GMT

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

I had a heading and a button to toggle its 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. Thats 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 cant 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 youre 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'));

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

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.
Its 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. Its important not to limit yourself to a specific framework/library and its possible only by having a strong JS base.
Never underestimate the knowledge youre gonna get just by looking at documentations, especially when theyre as good as Reacts.
Thank you for reading !


Original Link: https://dev.to/rubengabrielian/3-react-concepts-i-wish-i-knew-when-i-started-4bim

Share this article:    Share on Facebook
View Full Article

Dev To

An online community for sharing and discovering great ideas, having debates, and making friends

More About this Source Visit Dev To