Yes, as far as passing down props are concerned there is no difference in usage with React Hooks. In the snippet you've provided just pass setSearchData as a prop to PostContainer.

<PostContainer
  data={dataOnMap}
  addLike={addLike[index]}
  searchData={searchData}
  setSearchData={setSearchData}
/>
Answer from Deniz Tetik on Stack Overflow
🌐
Reddit
reddit.com › r/react › how would i pass state hook from parent to child?
r/react on Reddit: How would I pass state hook from parent to child?
May 5, 2022 -

Side note: I really wish the documentation was updated away from the class system. It seems like everyone has moved to hooks at the time of me learning react and the most valuable resource is hard to navigate due to that. It seems there are a many ways to pass state, and props across components, this is by far the most confusing to me current.

//App.js 
function App(){ 
const [count, setCount] useState=(0); return(
  <div>
    <Child setCount={setCount}/>
  </div>
 )
}

//Child.js 
const Child = () => {
function incrementCount(){
   setCount(count +1) }
  return( 
    <div> 
      <button onClick={decrementCount}> - </button> 
      <span>{count}</span> 
    </div> 
  ) 
}

Now my problem is, how do I give my child component access to “count” from my hook in app? I want to be able to define my functions away from app but give them access to state when I write them. <Child setCount={setCount} count={count}/> only works for setCount but when I put count like that it says “count not declared” and I cant access count in my child component functions.

Top answer
1 of 2
5
I think you are getting a few things confused here mate. Wish I knew how to code inside of a comment with the black background and vscode theme which would make this much easier to read, but here goes nothing: First of all, setState doesn't work in functional components. You need to use useState. The code will be as follows: const [count, setCount] = useState() You can specify a default value for count inside of the parentheses after useState. For example, if you want the default value to be 0, you can write useState(0). Also, don't forget to import useState from react or it won't work. Next, you need to define the function inside the parent component, and afterwards pass it down to the child. Move the incrementCount function to the parent component and pass it down as: setCount={incrementCount} The setCount can be any name you want. Next, inside the child component you need access to props, which is just how React calls state passed down from a parent component. You can destructure it, but let's keep it easy for now. The child component should be: const Child = (props) => { // Your code } See the props? That's how you get anything passed down from the parent. Now in your button you can access the function with props.setCount But these are really the basics of React, and if you are struggling with these I would recommend watching any YouTube video on react props and they will explain it 10 times better than I just did.
2 of 2
1
I know there is a whole thread down there, buy does this work: SetCount(prev, prev+1); // increment SetCount(prev, prev-1); // decrement
🌐
Medium
omarshishani.medium.com › how-to-prevent-passing-many-props-to-a-react-component-when-using-hooks-e870317504a5
How to Group State and Pass it Down to Children with React Hooks | by Omar Shishani | Medium
September 18, 2021 - Instead of passing all of that ... just save all of the state to an object, pass just the object to the child component, and then destructure the object to get all of the functions and variables out in the destination child...
🌐
Reddit
reddit.com › r/reactjs › is it bad to pass usestate as a prop to a component?
Is it bad to pass useState as a prop to a component? : r/reactjs
April 17, 2022 - In the original example, passing down setState makes the child component aware of the parent’s implementation, when it should be the other way around. Imagine a button that opens a dialog. If you call the prop “openDialog”, the button can only be used in this specific use case. But if you call the prop “onClick”, then the button can be used for other things. The functionality is the same, but wording makes the mental model much different. ... As a next step you might discover react context that allows you to teleport the state and its setter deep down the components tree.
🌐
Pragimtech
pragimtech.com › blog › reactjs › usestate-component-communication-in-react
useState for Sharing Data between Components in React
import ReactDOM from "react-dom"; import React, { Component, useState } from "react"; function NewEmployee(){ const [employee,setEmployeeData]=useState({Id:'',Name:'',Location:'',Salary:''}); function changeEmployeeInfo(e){ console.log(e); setEmployeeData({...employee,[e.target.name]:e.target.value}); } return( <div> <h2>Welcome to Employee Component...</h2> <p> <label>Employee ID : <input type="text" name="Id" value={employee.Id} onChange={changeEmployeeInfo}></input> </label> </p> <p> <label>Employee Name : <input type="text" name="Name" value={employee.Name} onChange={changeEmployeeInfo}></
🌐
YouTube
youtube.com › watch
React Hooks Basics: How to change parent state from within a child component (useState) | 2020 - YouTube
GITHUB REPOS: https://github.com/machieajones In video I show you how simple it is to set the parent component's state from within a child component. This ca...
Published   April 23, 2020
🌐
Pluralsight
pluralsight.com › tech insights & how-to guides › tech guides & tutorials
Passing State of Parent to Child Component as Props | Pluralsight
November 24, 2020 - Next, we will pass that piece of state to a child (Player) component for visualization purposes. Finally, we will set up a function to remove players one by one and see how that impacts the state of the parent.
Find elsewhere
🌐
LogRocket
blog.logrocket.com › home › the noob’s guide to usestate
The noob's guide to useState - LogRocket Blog
June 4, 2024 - Use React's useEffect to optimize your application's performance ... Advisory boards aren’t just for executives. Join LogRocket’s Content Advisory Board. You’ll help inform the type of content we create and get access to exclusive meetups, social accreditation, and swag · And don’t forget to add use as a prefix to your function name so you’re following the rules of hooks! This is basically the same bad practice as passing useState in the child component.
Top answer
1 of 7
132

A common technique for these situations is to lift the state up to the first common ancestor of all the components that needs to use the state (i.e. the PageComponent in this case) and pass down the state and state-altering functions to the child components as props.

Example

const { useState } = React;

function PageComponent() {
  const [count, setCount] = useState(0);
  const increment = () => {
    setCount(count + 1)
  }

  return (
    <div className="App">
      <ChildComponent onClick={increment} count={count} />         
      <h2>count {count}</h2>
      (count should be updated from child)
    </div>
  );
}

const ChildComponent = ({ onClick, count }) => {
  return (
    <button onClick={onClick}>
       Click me {count}
    </button>
  )
};

ReactDOM.render(<PageComponent />, document.getElementById("root"));
<script src="https://unpkg.com/react@16/umd/react.development.js"></script>
<script src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>

<div id="root"></div>

2 of 7
95

You can create a method in your parent component, pass it to child component and call it from props every time child's state changes, keeping the state in child component.

    const EnhancedTable = ({ parentCallback }) => {
        const [count, setCount] = useState(0);
        
        return (
            <button onClick={() => {
                const newValue = count + 1;
                setCount(newValue);
                parentCallback(newValue);
            }}>
                 Click me {count}
            </button>
        )
    };

    class PageComponent extends React.Component { 
        callback = (count) => {
            // do something with value in parent component, like save to state
        }

        render() {
            return (
                <div className="App">
                    <EnhancedTable parentCallback={this.callback} />         
                    <h2>count 0</h2>
                    (count should be updated from child)
                </div>
            )
        }
    }
🌐
SheCodes
shecodes.io › athena › 4369-passing-usestate-parameters-in-react-components
[React] - Passing useState Parameters in React Components - | SheCodes
Learn how to pass parameters between React components by leveraging `useState` and `setState` with an example.
🌐
Stack Overflow
stackoverflow.com › questions › 71722925 › how-to-pass-react-usestate-hook-from-parent-to-child-components
reactjs - How to pass react useState hook from parent to Child components - Stack Overflow
I am trying to pass a React hook ... updated. export default () => { const [fromDate, setFromDate] = useState(null); const [toDate, setToDate] = useState(null); } return html`<div className="cal"> <${Calendar} config=${config} setFromDate=......
🌐
React
react.dev › reference › react › useState
useState – React
The current state. During the first render, it will match the initialState you have passed. The set function that lets you update the state to a different value and trigger a re-render. useState is a Hook, so you can only call it at the top level of your component or your own Hooks.
🌐
React
react.dev › learn › sharing-state-between-components
Sharing State Between Components – React
To do it, remove state from both of them, move it to their closest common parent, and then pass it down to them via props. This is known as lifting state up, and it’s one of the most common things you will do writing React code.
🌐
GitHub
gist.github.com › tennox › 3b25845d2bf9c5204638fd18e3595d50
React: Pass useState hook to child · GitHub
React: Pass useState hook to child. GitHub Gist: instantly share code, notes, and snippets.
🌐
CopyProgramming
copyprogramming.com › howto › pass-setstate-from-parent-to-its-child-component-using-react-hook
Reactjs: Utilizing React Hook to Transmit setState from Parent Component to its Child
April 27, 2023 - pass setstate from parent to child component usestate setter to a child for updating parents state typescript usestate setstate in child with argument ... According to the React documentation, passing functions are the suggested properties to use when modifying the state variables of the parent ...
🌐
DEV Community
dev.to › pnkfluffy › passing-data-from-child-to-parent-with-react-hooks-1ji3
Passing Data from Child to Parent with React Hooks - DEV Community
March 30, 2020 - Using functions is a great way to pass data up component trees. It can be used in many ways, most notably rendering based off of user interactions / inputs made in child components. Using this trick with react hooks helps in writing beautiful, maintainable code, as it is easy to follow the flow of logic through functional components and functions themselves.
Top answer
1 of 7
100

The type that would match the function returned from invoking useState would be:

setMyVar: (value: boolean | ((prevVar: boolean) => boolean)) => void;

If we look at the type definition file from DefinitelyTyped [1], we can see that the second type in the return type is a dispatch:

function useState<S>(initialState: S | (() => S)): [S, Dispatch<SetStateAction<S>>];

Thus the generic type provided is passed through to SetStateAction<S>, which is defined as:

type SetStateAction<S> = S | ((prevState: S) => S);

So essentially, an interface for your component would be the following:

interface IProps {
  myVar: boolean;
  setMyVar?: (value: boolean | (prevVar: boolean) => boolean) => void;
}

As @Retsam said, it's best to use React's exported types:

import { Dispatch, SetStateAction } from "react";

interface IProps {
  myVar: boolean;
  setMyVar?: Dispatch<SetStateAction<boolean>>;
}

References: [1] https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/react/index.d.ts#L845

2 of 7
35

Dispatch & SetStateAction types

As @Retsam mentioned, you can also import and use the types Dispatch and SetStateAction from React:

import React, { Dispatch, SetStateAction } from 'react';

const MyChildComponent1 = (
  myVar: boolean,
  setMyVar: Dispatch<SetStateAction<boolean>>
) => {...};

Bonus

When I find myself frequently using this, I create a type alias to help with readability

import React, { Dispatch, SetStateAction } from 'react';

type Dispatcher<S> = Dispatch<SetStateAction<S>>;

const MyChildComponent1 = (
  myVar: boolean,
  setMyVar: Dispatcher<boolean>,
) => {...};

hope this helps.

🌐
GitHub
github.com › reactjs › react.dev › issues › 1689
how to change the state of parent component from child Component if parent state is maintained using useStateHook · Issue #1689 · reactjs/react.dev
February 15, 2019 - But I am maintaining the parent component state using useState hook . So i am not getting access to the function to change this state from the child component .
Author   girishts
🌐
Medium
uros-randelovic.medium.com › how-to-update-the-state-and-pass-data-from-child-to-parent-in-react-hooks-56ca26626c31
How to update the state and pass data from child to parent in React (Hooks) | by Uros Randelovic | Medium
February 18, 2020 - How to update the state and pass data from child to parent in React (Hooks) Note: I assume that you are somewhat familiar with React Hooks So you want the child to update the data in the parent… …