Ask Your Question
0

How can state management be achieved using either useContext or EventEmitter in React?

asked 2023-01-18 11:00:00 +0000

plato gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
3

answered 2021-04-25 16:00:00 +0000

djk gravatar image

State management in React can be achieved using either useContext or EventEmitter.

  1. Using useContext:
  2. Create a context using createContext() method.
  3. Define a provider that provides the state and the methods to manipulate the state.
  4. Wrap the components that need access to the state using the provider.

Example code:

const MyContext = React.createContext();

function MyProvider(props) {
  const [state, setState] = useState(initialState);

  const updateState = (newValue) => {
    setState(newValue);
  };

  return (
    <MyContext.Provider value={{ state, updateState }}>
      {props.children}
    </MyContext.Provider>
  );
}

function MyComponent() {
  const { state, updateState } = useContext(MyContext);

  return (
    <div>
      <p>Current state: {state}</p>
      <button onClick={() => updateState(newState)}>Update state</button>
    </div>
  );
}

  1. Using EventEmitter:
  2. Create an EventEmitter using the EventEmitter class from the events module.
  3. Define events and listeners to manipulate the state.
  4. Emit events from the components that trigger state changes.

Example code:

// Import EventEmitter from events module
import { EventEmitter } from "events";

// Create an instance of EventEmitter
const myEventEmitter = new EventEmitter();

// Define events and listeners
myEventEmitter.on("updateState", (newState) => {
  // update the state
});

// Emit events from components
function MyComponent() {
  return (
    <div>
      <button
        onClick={() => {
          myEventEmitter.emit("updateState", newState);
        }}
      >
        Update state
      </button>
    </div>
  );
}

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2023-01-18 11:00:00 +0000

Seen: 9 times

Last updated: Apr 25 '21