React Custom Hooks: Reusable Stateful Logic

React Interview Question: What are Custom Hooks in React? Answer: Custom hooks are JavaScript functions that allow you to reuse stateful logic across multiple components. They follow the naming convention starting with "use". Example: 𝘧𝘶𝘯𝘤𝘵𝘪𝘰𝘯 𝘶𝘴𝘦𝘞𝘪𝘯𝘥𝘰𝘸𝘞𝘪𝘥𝘵𝘩() {  𝘤𝘰𝘯𝘴𝘵 [𝘸𝘪𝘥𝘵𝘩, 𝘴𝘦𝘵𝘞𝘪𝘥𝘵𝘩] = 𝘶𝘴𝘦𝘚𝘵𝘢𝘵𝘦(𝘸𝘪𝘯𝘥𝘰𝘸.𝘪𝘯𝘯𝘦𝘳𝘞𝘪𝘥𝘵𝘩)  𝘶𝘴𝘦𝘌𝘧𝘧𝘦𝘤𝘵(() => {   𝘤𝘰𝘯𝘴𝘵 𝘩𝘢𝘯𝘥𝘭𝘦𝘙𝘦𝘴𝘪𝘻𝘦 = () => 𝘴𝘦𝘵𝘞𝘪𝘥𝘵𝘩(𝘸𝘪𝘯𝘥𝘰𝘸.𝘪𝘯𝘯𝘦𝘳𝘞𝘪𝘥𝘵𝘩)   𝘸𝘪𝘯𝘥𝘰𝘸.𝘢𝘥𝘥𝘌𝘷𝘦𝘯𝘵𝘓𝘪𝘴𝘵𝘦𝘯𝘦𝘳("𝘳𝘦𝘴𝘪𝘻𝘦", 𝘩𝘢𝘯𝘥𝘭𝘦𝘙𝘦𝘴𝘪𝘻𝘦)   𝘳𝘦𝘵𝘶𝘳𝘯 () => 𝘸𝘪𝘯𝘥𝘰𝘸.𝘳𝘦𝘮𝘰𝘷𝘦𝘌𝘷𝘦𝘯𝘵𝘓𝘪𝘴𝘵𝘦𝘯𝘦𝘳("𝘳𝘦𝘴𝘪𝘻𝘦", 𝘩𝘢𝘯𝘥𝘭𝘦𝘙𝘦𝘴𝘪𝘻𝘦)  }, [])  𝘳𝘦𝘵𝘶𝘳𝘯 𝘸𝘪𝘥𝘵𝘩 } Explanation: Custom hooks help: 1. reuse logic 2. reduce duplicate code 3. improve component readability Follow-up Interview Question: Do custom hooks share state between components? Answer: No. Explanation: Each component calling the hook gets its own independent state instance. #reactjs #CustomHooks #FrontendDevelopment #WebDevelopment

To view or add a comment, sign in

Explore content categories