useState vs Normal Variables in React Components

💡React Interview Question💡 Why do we always use useState, useRef, useReducer hook to store any information in the functional component instead of using normal variables? Answer: Whenever we create a React functional component, React behind the scenes creates a JavaScript function, and uses bind method to pass the props as arguments for each component like this: const User = User.bind(null, { userId: 10, username: 'Mike' }) Here, because of the bind method so we can re-use that component later multiple times with different props like this: <User userId={10} username="Mike" /> <User userId={12} username="Jerry" /> And because 𝗨𝘀𝗲𝗿 component is converted to a JavaScript function, each time you call that function, all the local variables, event handlers declared in the component will be re-created on every function call/re-render of the component. That's the reason we use hooks like 𝘂𝘀𝗲𝗦𝘁𝗮𝘁𝗲, 𝘂𝘀𝗲𝗥𝗲𝗱𝘂𝗰𝗲𝗿 or 𝘂𝘀𝗲𝗥𝗲𝗳 to store the values inside the component to retain the values across multiple re-renders. Even though we declare state or ref in a component, state or ref value is actually stored outside the component linked to that particular component, that's why we don't loose its value during re-render. If we declare a local variable 𝗰𝗼𝘂𝗻𝘁𝗲𝗿 along with the 𝘂𝘀𝗲𝗦𝘁𝗮𝘁𝗲 hook inside a 𝗨𝘀𝗲𝗿 component like this: 𝘧𝘶𝘯𝘤𝘵𝘪𝘰𝘯 𝘜𝘴𝘦𝘳() { 𝘤𝘰𝘯𝘴𝘵 [𝘶𝘴𝘦𝘳, 𝘴𝘦𝘵𝘜𝘴𝘦𝘳] = 𝘶𝘴𝘦𝘚𝘵𝘢𝘵𝘦(𝘯𝘶𝘭𝘭); 𝘤𝘰𝘯𝘴𝘵 𝘤𝘰𝘶𝘯𝘵𝘦𝘳 = 𝟣𝟢; 𝘤𝘰𝘯𝘴𝘵 𝘩𝘢𝘯𝘥𝘭𝘦𝘊𝘭𝘪𝘤𝘬 = (𝘦𝘷𝘦𝘯𝘵) => { // 𝘴𝘰𝘮𝘦 𝘤𝘰𝘥𝘦 } // 𝘴𝘰𝘮𝘦 𝘑𝘚𝘟 } then the 𝗰𝗼𝘂𝗻𝘁𝗲𝗿 variable and 𝗵𝗮𝗻𝗱𝗹𝗲𝗖𝗹𝗶𝗰𝗸 method will be re-created on every re-render of the 𝗨𝘀𝗲𝗿 component so 𝗰𝗼𝘂𝗻𝘁𝗲𝗿 variable value will be reset to 𝟭𝟬 on every re-render of the component, but the 𝘂𝘀𝗲𝗿 state will maintain its previous value across multiple re-render of the 𝗨𝘀𝗲𝗿 component and it 𝘄𝗶𝗹𝗹 𝗻𝗼𝘁 𝗯𝗲 re-initialized to null on re-render. Because even though the state is declared inside a component, React actually stores the state information outside the component so as to not lose its value during re-render. 𝗙𝗼𝗿 𝗺𝗼𝗿𝗲 𝘀𝘂𝗰𝗵 𝘂𝘀𝗲𝗳𝘂𝗹 𝗰𝗼𝗻𝘁𝗲𝗻𝘁, 𝗱𝗼𝗻'𝘁 𝗳𝗼𝗿𝗴𝗲𝘁 𝘁𝗼 𝗳𝗼𝗹𝗹𝗼𝘄 𝗺𝗲. #javascript #reactjs #nextjs #webdevelopment

To view or add a comment, sign in

Explore content categories