Event-driven approach in React?

Viewed 11028

I'd like to "fire an event" in one component, and let other components "subscribe" to that event and do some work in React.

For example, here is a typical React project.

I have a model, fetch data from server and several components are rendered with that data.

interface Model {
   id: number;
   value: number;
}

const [data, setData] = useState<Model[]>([]);
useEffect(() => {
   fetchDataFromServer().then((resp) => setData(resp.data));
}, []);

<Root>
   <TopTab>
     <Text>Model with large value count:  {data.filter(m => m.value > 5).length}</Text>
   </TobTab>
   <Content>
      <View>
         {data.map(itemData: model, index: number) => (
            <Item key={itemData.id} itemData={itemData} />
         )}
      </View>
   </Content>
   <BottomTab data={data} />
</Root>

In one child component, a model can be edited and saved.

const [editItem, setEditItem] = useState<Model|null>(null);
<Root>
   <TopTab>
     <Text>Model with large value count:  {data.filter(m => m.value > 5).length}</Text>
   </TobTab>
   <ListScreen>
      {data.map(itemData: model, index: number) => (
          <Item 
             key={itemData.id} 
             itemData={itemData} 
             onClick={() => setEditItem(itemData)}
          />
      )}
   </ListScreen>
   {!!editItem && (
       <EditScreen itemData={editItem} />
   )}
   <BottomTab data={data} />
</Root>

Let's assume it's EditScreen:

const [model, setModel] = useState(props.itemData);

<Input 
   value={model.value}
   onChange={(value) => setModel({...model, Number(value)})}
/>
<Button 
   onClick={() => {
       callSaveApi(model).then((resp) => {
           setModel(resp.data);
           // let other components know that this model is updated
       })
   }}
/>

App must let TopTab, BottomTab and ListScreen component to update data

  • without calling API from server again (because EditScreen.updateData already fetched updated data from server) and
  • not passing updateData function as props (because in most real cases, components structure is too complex to pass all functions as props)

In order to solve above problem effectively, I'd like to fire an event (e.g. "model-update") with an argument (changed model) and let other components subscribe to that event and change their data, e.g.:

// in EditScreen
updateData().then(resp => {
   const newModel = resp.data;
   setModel(newModel);
   Event.emit("model-updated", newModel);
});

// in any other components
useEffect(() => {
   // subscribe model change event
   Event.on("model-updated", (newModel) => {
      doSomething(newModel);
   });
   // unsubscribe events on destroy
   return () => {
     Event.off("model-updated");
   }
}, []);

// in another component
useEffect(() => {
   // subscribe model change event
   Event.on("model-updated", (newModel) => {
      doSomethingDifferent(newModel);
   });
   // unsubscribe events on destroy
   return () => {
     Event.off("model-updated");
   }
}, []);

Is it possible using React hooks?

How to implement event-driven approach in React hooks?

5 Answers

There cannot be an alternative of event emitter because React hooks and use context is dependent on dom tree depth and have limited scope.

Is using EventEmitter with React (or React Native) considered to be a good practice?

A: Yes it is a good to approach when there is component deep in dom tree

I'm seeking event-driven approach in React. I'm happy with my solution now but can I achieve the same thing with React hooks?

A: If you are referring to component state, then hooks will not help you share it between components. Component state is local to the component. If your state lives in context, then useContext hook would be helpful. For useContext we have to implement full context API with MyContext.Provider and MyContext.Consumer and have to wrap inside high order (HOC) component Ref

so event emitter is best.

In react native, you can use react-native-event-listeners package

yarn add react-native-event-listeners

SENDER COMPONENT

import { EventRegister } from 'react-native-event-listeners'

const Sender = (props) => (
    <TouchableHighlight
        onPress={() => {
            EventRegister.emit('myCustomEvent', 'it works!!!')
        })
    ><Text>Send Event</Text></TouchableHighlight>
)

RECEIVER COMPONENT

class Receiver extends PureComponent {
    constructor(props) {
        super(props)
        
        this.state = {
            data: 'no data',
        }
    }
    
    componentWillMount() {
        this.listener = EventRegister.addEventListener('myCustomEvent', (data) => {
            this.setState({
                data,
            })
        })
    }
    
    componentWillUnmount() {
        EventRegister.removeEventListener(this.listener)
    }
    
    render() {
        return <Text>{this.state.data}</Text>
    }
}

Not sure why the EventEmitter has been downvoted, but here's my take:

When it comes to state management, I believe using a Flux-based approach is usually the way to go (Context/Redux and friends are all great). That said, I really don't see why an event-based approach would pose any problem - JS is event based and React is just a library after all, not even a framework, and I can't see why we would be forced to stay within its guidelines.

If your UI needs to know about the general state of your app and react to it, use reducers, update your store, then use Context/Redux/Flux/whatever - if you simply need to react to specific events, use an EventEmitter.

Using an EventEmitter will allow you to communicate between React and other libraries, e.g. a canvas (if you're not using React Three Fiber, I dare you to try and talk with ThreeJS/WebGL without events) without all the boilerplate. There are many cases where using Context is a nightmare, and we shouldn't feel restricted by React's API.

If it works for you, and it's scalable, just do it.

EDIT: here's an example using eventemitter3:

./emitter.ts

import EventEmitter from 'eventemitter3';

const eventEmitter = new EventEmitter();

const Emitter = {
  on: (event, fn) => eventEmitter.on(event, fn),
  once: (event, fn) => eventEmitter.once(event, fn),
  off: (event, fn) => eventEmitter.off(event, fn),
  emit: (event, payload) => eventEmitter.emit(event, payload)
}

Object.freeze(Emitter);

export default Emitter;

./some-component.ts

import Emitter from '.emitter';

export const SomeComponent = () => {
  useEffect(() => {
    // you can also use `.once()` to only trigger it ... once
    Emitter.on('SOME_EVENT', () => do what you want here)
    return () => {
      Emitter.off('SOME_EVENT')
    }
  })
}

From there you trigger events wherever you want, subscribe to them, and act on it, pass some data around, do whatever you want really.

We had a similar problem and took inspiration from useSWR.

Here is a simplified version of what we implemented:

const events = [];
const callbacks = {};

function useForceUpdate() {
   const [, setState] = useState(null);
   return useCallback(() => setState({}), []);
}

function useEvents() {

    const forceUpdate = useForceUpdate();
    const runCallbacks = (callbackList, data) => {
       if (callbackList) {
          callbackList.forEach(cb => cb(data));
          forceUpdate();
       }
     
    }

    const dispatch = (event, data) => {
        events.push({ event, data, created: Date.now() });
        runCallbacks(callbacks[event], data);
    }

    const on = (event, cb) => {
        if (callbacks[event]) {
           callbacks[event].push(cb);
        } else {
          callbacks[event] = [cb];
        }

        // Return a cleanup function to unbind event
        return () => callbacks[event] = callbacks[event].filter(i => i !== cb);
    }

    return { dispatch, on, events };
}

In a component we do:

const { dispatch, on, events } = useEvents();

useEffect(() => on('MyEvent', (data) => { ...do something...}));

This works nicely for a few reasons:

  1. Unlike the window Event system, event data can be any kind of object. This saves having to stringify payloads and what not. It also means there is no chance of collision with any built-in browser events
  2. The global cache (idea borrowed from SWR) means we can just useEvents wherever needed without having to pass the event list & dispatch/subscribe functions down component trees, or mess around with react context.
  3. It is trivial to save the events to local storage, or replay/rewind them

The one headache we have is the use of the forceUpdate every time an event is dispatched means every component receiving the event list is re-rendered, even if they are not subscribed to that particular event. This is an issue in complex views. We are actively looking for solutions to this...

You can create use context in App.js using useContext, and then in you child component you can use values from it and update the context as soon as the context get updated it will update the values being used in other child component, no need to pass props.

You can achieve this with any React's global state management.

In your store, have a useEffect for your event subscription, and a reducer for each of your event.

If you have 2 data sources, the subscription and the query, then initialize your state values with your query, then listen to the subscription.

Something like this

const reducer = (state, action) => {
   switch(action.type) {
     case 'SUBSCRIBE':
        return action.payload
     default:
        return state
   }
}

Assuming you are using https://github.com/dai-shi/use-reducer-async

const asyncActions = {
   QUERY: ({ dispatch }) => async(action) => {
     const data = await fetch(...)
     dispatch({ type: 'query', payload: data })
   }
}

You can also use middleware in Redux

const [state, dispatch] = useReducer(reducer, initialValues, asyncActions)

useEffect(() => {
   dispatch({ type: 'QUERY' })
   Event.on((data) => {
      dispatch({ type: 'SUBSCRIBE', payload: data })
   })
   return () => Event.off()
}, [])

return <Provider value={state}>{children}</Provider>
Related