Home > Blockchain >  How i can change UI on change redux-toolkit state?
How i can change UI on change redux-toolkit state?

Time:05-21

I want to rerender my component when i'm dispatch from another component, how i can do it?

Component that need for rerender:

const MessageComponent = (): JSX.Element => {
    const [messages, setMessages] = useState<IMessageComponentState>({
        messages: []
    })

    const message = useSelector((state: RootState) => state.message.messages);

    useEffect(() => {
        setMessages({
            messages: message
        })
        console.log(message)
    }, message);



    return (
        <>
            {messages.messages}
            <MyMessageComponent  message="some text"/>
            <IncomeMessageComponent  message="some text2"/>
        </>

    )
}

CodePudding user response:

Dependency in useEffect have to put inside [ ]. See more: Conditionally firing an effect.

And messages state is an array but you set a object, change from setMessages({ messages: message }) to setMessages((mes) => [...mes, {messages: message}])

const MessageComponent = (): JSX.Element => {
    const [messages, setMessages] = useState<IMessageComponentState>({
        messages: []
    })

    const message = useSelector((state: RootState) => state.message.messages);

    useEffect(() => {
        setMessages((mes) => [...mes, {
            messages: message
        }])
        console.log(message)
    }, [message]); //<=== Put message in []



    return (
        <>
            {messages.messages}
            <MyMessageComponent  message="some text"/>
            <IncomeMessageComponent  message="some text2"/>
        </>

    )
}

CodePudding user response:

This will cause re-render.

If you need more to re-render, like the <MyMessageComponent /> or the `, they'd just need to have some form of conditional rendering attached to the message variable or use it.

The primary value of post-react-hooks redux is the rendering, or rather, the lack thereof; it only re-renders what it absolutely has to, i.e., components that require the change directly.

  • Related