How to pass a parameter from useEffect to child component in React?

Solution 1:

Create a state variable with useState.

Modify that variable inside your useEffect hook.

The variable will then be in scope for the rest of your component and you can pass it as a prop.


Make sure you handle the default state from before the effect hook has run (e.g. with a sane default value or a value that indicates a <Loading /> component should be rendered instead of <ChatInput />)

Solution 2:

You can utilize the useState hook to create a variable for storing channelNameData.

import { useState } from 'react';

const [channelNameDataState, setChannelNameDataState] = useState(null)

Inside your useEffect, you can have a line that sets channelNameDataState.

setChannelNameDataState(channelNameData)

Then you would pass in this state to the child component

<ChatInput
  channelName={channelNameDataState}
  channelId={roomId}
/>

As for preventing assignments to the channelNameData variable getting lost, you should be able to combine the useState hook with localState to make sure you can persist state.