Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

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