Skip to content

Latest commit

 

History

History
81 lines (59 loc) · 2.52 KB

8.Hooks_useContext_useReducer.md

File metadata and controls

81 lines (59 loc) · 2.52 KB

100 React Questions (Hooks - useContext/useReducer)

Q1. What is the role of useContext() hook? V. IMP.

useContext in React provides a way to pass data from parent to child component without using props.

MyContext.js

import { createContext } from "react";

const MyContext = createContext();
export default MyContext;

Parent.js

const Parent = () => {
    const contextValue = "Hello from Context!";
    
    return (
        <MyContext.Provider value={contextValue}>
            {/* Your component tree */}
            <Child />
        </MyContext.Provider>
    );
};
export default Parent;

Child.js

const Child = () => {
    const contextValue = useContext(MyContext);

    return <p>{contextValue}</p>;

    // return (
    // <MyContext.Consumer>
    //     {(contextValue) => <div>{contextValue}</div>}
    // </MyContext.Consumer>
    // );
};
export default Child;

Q2. What is createContext() method? What are Provider & Consumer properties?

  • The createContext() function returns an object with Provider and Consumer properties.

  • The Provider property is responsible for providing the context value to all its child components.

  • The useContext() method or Consumer property can be used to consume the context value in child components.

Q3. When to use useContext() hook instead of props in real applications?

Use useContext instead of props when you want to avoid prop drilling and access context values directly within deeply nested components.

Feature Description
Theme Switching (Dark/Light) Centralize and pass theme selection from parent to all child components.
Localization (Language Selection) Centralize and pass language selection from parent to all child components.
Centralize Configuration Settings Centralize common settings like API endpoints. Changes in parent affect all children.
User Preferences Centralize user preferences beyond theme and localization.
Notification System Access notification state from context for components triggering or displaying notifications.

Q4. What are the similarities between useState() and useReducer() hook?

Q5. What is useReducer() hook? When to use useState() and when useReducer()? V. IMP.

Q6. What are the differences between useState() and useReducer() Hook?

Q7. What are dispatch & reducer function in useReducer Hook?

Q8. What is the purpose of passing initial state as an object in UseReducer?