How to pass data from one component to another in react without re-render or jsx like from a function using functional components

Viewed 38

I am new to react and I am not getting any answers on this.

I want to pass data from one functional component to another in react. However I do not want to render the child component. I just want to pass the data from one component to another. How do I achieve this?

Please help

There has to be a way to do this.

2 Answers

Simply do not return anything from the functional component that you don't want to render.

A functional component renders whatever the return statement returns.

If I understand you correct, you want to pass data as prop to child component and do not want it to be re-rendered.

Let's define a functional component using React.memo so that it will not be re-rendered unless its props changes.

mine.js

import React from "react";

const Mine = React.memo((props) => {
  console.log('renders')
  return <h1>HI!</h1>
})

Now we call it inside our app

App.js

import React, { useState, useMemo } from "react";

export default function App() {
  const arr = useMemo(() => [1,2,3], []);
  const [counter, setCounter] = useState(0);

  const onClickHandler = (e) => {
    let c = counter;
    setCounter(c+1);
  }

  return (
    <div className="App">
      <h1>{counter}</h1>
      <button onClick={onClickHandler}>Click</button>
      <Mine arr={arr} />
    </div>
  );
}

If you take your attention to console.log, you are going to see that component Mine will not be re-rendered even the parent component state changes when you press the button. Pressing the button will cause a re-render on parent component, app, but child component will stay same. We passed a prop called arr to the child component and we wrapped it with useMemo. If you remove useMemo, you will see that it will cause child component, mine, to be re-rendered. So we memoized data.

I guess this is what you want.

Sandbox

Related